Main Page

From wiki
Jump to: navigation, search

Contents

Getting Started

Smart Persistence is a simple PHP object relational mapping framework. It sits on top of the Zend Framework, leveraging the Zend Framework. It is a JPA look-like for PHP.

The Zend Framework is probably the future of PHP Web Application development, Smart Persistence ORM layer plugs into the Zend Framework, leveraging its services.

Prepare Database Table

Step step is to create the database table. The database table is called simple. If using Mysql the table might look like:

CREATE
    TABLE simple
    (
        id INT NOT NULL AUTO_INCREMENT COMMENT 'Auto generated id.',
        employee_name VARCHAR(80) NOT NULL,
        employee_lastname VARCHAR(80) NOT NULL,
        date_of_birth DATE NOT NULL,
        salary DECIMAL NOT NULL,
        children TINYINT,
        married bit,
        employee_number VARCHAR(15) NOT NULL,
        PRIMARY KEY (id),
        CONSTRAINT id_UNIQUE UNIQUE (id),
        CONSTRAINT employee_number_unique UNIQUE (employee_number)
    )
    ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT=
    'Demostrates how to read and write a simple table.'

Create Entity Class

After creating the database table, create the corresponding entity model class. In this example the entity model classes is called Client_Simple_Employee.

Create Metadata

Since PHP is an interpreted language, so in order for the framework to know that this is an entity, more information is added into the source, as comment tags. The comment tags added to the PHP source contains all the information required by the framework to create, read, update and delete records in the database table.

To generate usable code from comments execute the command:

%SMART_FRAMEWORK%/sp.bat %PROJECT_HOME%/application/configs/spconfig.ini

where
:


The smart persistence configuration file syntax currently looks as follows:

; Smart Persistence Configuration file
;comma separated list of all class packages to be processed.
code.packages = Client.Simple
code.classpath = %PROJECT_HOME%/library;

%PROJECT_HOME% - must be a full path target project directory. Typically Zend Framework project.

Configure the Entity Manager

Configure the entity manager in application.ini of the Zend project.

resources.view[] = ''
;to make the entity manager available as a plugin
resources.view.helperPath.Smart_Persistence_Helper = SP_PATH "/Smart/Persistence/Helper"

;to make the entity manager available as a resource
pluginPaths.Smart_Persistence_Resource = SP_PATH "/Smart/Persistence/Resource"

resources.spu.db1.adapter = Pdo_Mysql
resources.spu.db1.params.host = localhost
resources.spu.db1.params.username = sp
resources.spu.db1.params.password = password
resources.spu.db1.params.dbname = smartpersist
resources.spu.db1.log.stream.writerName = "Stream"
resources.spu.db1.log.stream.writerParams.stream = APPLICATION_PATH "/data/logs/spu.log"
resources.spu.db1.log.stream.writerParams.mode = "a"
resources.spu.db1.log.stream.filterName = "Priority"
resources.spu.db1.log.stream.filterParams.priority = 7

Create, Read, Update Delete Examples

The last step is to use the entity manager inside an action controller

Read

  1.     /**
  2.      * Entity manager.
  3.      * 
  4.      * @var Smart_Persistence_EntityManager
  5.      */
  6.     private $em = null;
  7.  
  8.     public function init(){
  9.       $bootstrap = Zend_Controller_Front::getInstance()
  10.                     ->getParam('bootstrap');
  11.  
  12.       if ($bootstrap->hasPluginResource('spu')){
  13.         $this->em = $bootstrap->getPluginResource('spu')
  14.                     ->getEntityManager();
  15.       }
  16.     }
  17.  
  18.     public function indexAction() {
  19.       //list all the employees.
  20.       $this->view->employees = $this->em->createQuery("SELECT e FROM Client.Simple.Employee e ")
  21.                                         ->getResultSet();
  22.       $page = $this->getRequest()->getParam("page");
  23.       if (is_numeric($page) && $page > 0){
  24.         $this->view->employees->setCurrentPageNumber($page);
  25.       }
  26.     }

Or can be used in specific ways:

  1. //read by primary key
  2. $employee = $this->em->find('Client.Simple.Employee',3);
  3. //the returned object is of type Client.Simple.Employee not just an array of data.
  4.  
  5. //find bulk records the result is always the Zend_Paginator
  6. //all items returned by this list are of type Client.Simple.Employee not just arrays of data.
  7. $all = em->createQuery('SELECT s FROM Client.Simple.Employee s')
  8.            ->getResultList();
  9.  
  10. //find a record using a criteria.
  11. $employee = $em->createQuery('SELECT s FROM Client.Simple.Employee s WHERE s.number=:number')
  12.                       ->setParameters(array('number'=>'R977874I'))
  13.                        ->getSingleResult();


Create

How about creating a new database record? Its as easy as this

  1. //you can create the new model by passing the values in an array of the constructor.
  2. $employee = new Client_Simple_Employee($_POST);
  3. //or doing it the old fashioned way.
  4. $employee->setFirstName('Tinashe')
  5.      ->setLastName('Chipomho');
  6. $employee = $this->em->merge($employee);

That's is all, the persistence framework have enough information, to locate the database table, map the values in the model to the appropriate columns in the table insert a record in the table and generate the id and return another instance of the model which is persistence aware.

Delete

Lets try to delete our object from the database.

  1. //remove the entity.
  2. $this->em->remove($employee);

Update

How about updating the record, simply update the properties and save it back.

  1. //get a raise
  2. $employee->setSalary(new Zend_Currency(array('value'=>450.00));
  3. $this->em->merge($employee);

That's all. More examples of Inheritance to follow:

MediaWiki has been successfully installed.

Consult the User's Guide for information on using the wiki software.

Personal tools
Namespaces
Variants
Actions
Smart Persistence
Toolbox