![]() |
|
Snippets |
|
It took me quite some time but here is how to execute a MySQL stored procedure.
$connection = Propel::getConnection(); $query = 'CALL Proc(%s, %s, %s)'; $query = sprintf($query, $var1, $var2, $var3); $mysqli = $connection->getResource(); if($mysqli->multi_query($query)){ do{ if($result = $mysqli->use_result()){ while($row = $result->fetch_assoc()){ // } $result->free(); } } while(($mysqli->next_result())); }
Note that you should be using mysqli in order for this to work properly.
I needed to have many subclasses inherited from a main class.
To do that with propel, you need to have all your classes in one big table. I wanted to have separate tables.
Then I discovered the propel behaviors and it does that very well !
Let's see an example with a master class "element" and a subclass "subElement" :
The tables of the subclasses just need to have an "element_id" foreign key column, to be linked with the "element" master class table :
# schema.yml example propel: # master class element: _attributes: { phpName: Element } id: name: varchar(255) content: longvarchar created_at: # subclass with only the subclass properties and element_id foreign key column sub_element: _attributes: { phpName: SubElement } element_id: author: varchar(255)
Activate the behaviors in "project/config/propel.ini" (before building the model!):
propel.builder.AddBehaviors = true
Don't forget to rebuild the model, anytime you modify it :
>symfony propel-build-model
Create your behavior in "project/config/config.php" :
// get propel behavior lib require_once($sf_symfony_lib_dir.'/addon/propel/sfPropelBehavior.class.php'); // declare all the methods from of the master class "element", that you'll need in the subclasses sfPropelBehavior::registerMethods('ElementBehavior', array( array('ElementBehavior', 'setName'), array('ElementBehavior', 'getName'), array('ElementBehavior', 'setContent'), array('ElementBehavior', 'getContent'), array('ElementBehavior', 'setCreated'), array('ElementBehavior', 'getCreatedAt'), ) ); // Modify save() and delete() master class methods // SubElement->save() need to run Element->save()..., and so for SubElement->delete() sfPropelBehavior::registerHooks('ElementBehavior', array( ':save:pre' => array('ElementBehavior', 'preSave'), ':delete:pre' => array('ElementBehavior', 'preDelete'), ) );
Declare all these behavior methods in the master class model (here in "project/lib/model/Element.php") :
// declare this class after the element class class ElementBehavior { /* Properties Setters */ public function setName(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setName($value); } public function setContent(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setContent(value); } public function setCreatedAt(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setCreatedAt($value); } /* Properties Getters */ public function getId(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getId(); } public function getName(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getName(); } public function getContent(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getContent(); } public function getCreatedAt(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getCreatedAt(); } /* Element save method called just before SubElement save */ public function preSave(BaseObject $object) { // if element not null... if ($object->getElement()) { // save element in his table $object->getElement()->save(); // if new element, capture id if ($object->isNew()) $object->setElementId($object->getElement()->getId()); } } /* Element delete method called just before SubElement delete */ public function preDelete(BaseObject $object) { // if element not null and not new... if ($object->getElement() && !$object->getElement()->isNew()) { // delete element in his table $object->getElement()->delete(); } } }
add the "ElemenBehavior" to all your subclasses (here in" project/lib/model/SubElement.php") :
sfPropelBehavior::add('SubElement', array('ElementBehavior'));
That's all ! You can test it with a code like this :
// create subElement $test = new SubElement(); // test on element methods $test->setName('test'); $test->setContent('this is the big test !'); // test also SubElement methods $test->setAuthor('mr john smith'); // save in element table AND in sub_element table ! $test->save(); // capture subElement with id 1 $test = SubElementPeer :: retrieveByPk(1); // delete element and subElement in the two tables $test->delete(); // mix criteria for both class $c = new Criteria(); $c->add(ElementPeer :: ID, 1); $c->add(SubElementPeer :: AUTHOR, 'mr john smith'); // get a list of the subElements $subElements = SubElementPeer :: doSelectJoinElement(new Criteria());
each time you add a column or a method to the element model, you need to declare it in the behavior to be handled in the subclasses.
It's a way to go, may be there is a simplier way, but this works well for me...
I needed to have many subclasses inherited from a main class.
To do that with propel, you need to have all your classes in one big table. I wanted to have separate tables.
Then I discovered the propel behaviors and it does that very well !
Let's see an example with a master class "element" end a subclass "subElement" :
The tables of the subclasses just need to have an "element_id" foreign key column, to be linked with the "element" master class table :
# schema.yml example propel: # master class element: _attributes: { phpName: Element } id: name: varchar(255) content: longvarchar created_at: # subclass with only the subclass properties and element_id foreign key column sub_element: _attributes: { phpName: SubElement } element_id: author: varchar(255)
Activate the behaviors in "project/config/propel.ini" :
propel.builder.AddBehaviors = trueCreate your behavior in "project/config/config.php" :
// get propel behavior lib require_once($sf_symfony_lib_dir.'/addon/propel/sfPropelBehavior.class.php'); // declare all the methods from of the master class "element", that you'll need in the subclasses sfPropelBehavior::registerMethods('ElementBehavior', array( array('ElementBehavior', 'setName'), array('ElementBehavior', 'getName'), array('ElementBehavior', 'setContent'), array('ElementBehavior', 'getContent'), array('ElementBehavior', 'setCreated()'), array('ElementBehavior', 'getCreatedAt()'), ) ); // Modify save() and delete() master class methods // SubElement->save() need to run Element->save()..., and so for SubElement->delete() sfPropelBehavior::registerHooks('ElementBehavior', array( ':save:pre' => array('ElementBehavior', 'preSave'), ':delete:pre' => array('ElementBehavior', 'preDelete'), ) );
Declare all these behavior methods in the master class model (here in "project/lib/model/Element.php") :
// declare this class after the element class class ElementBehavior { /* Properties Setters */ public function setName(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setName($value); } public function setContent(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setContent(value); } public function setCreatedAt(BaseObject $object, $value) { if (!$object->getElement()) $object->setElement(new Element()); $object->getElement()->setDescription($value); } /* Properties Getters */ public function getId(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getId(); } public function getName(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getName(); } public function getContent(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getContent(); } public function getCreatedAt(BaseObject $object) { if (!$object->getElement()) $object->setElement(new Element()); return $object->getElement()->getCreatedAt(); } /* Element save method called just before SubElement save */ public function preSave(BaseObject $object) { // if element not null... if ($object->getElement()) { // save element in his table $object->getElement()->save(); // if new element, capture id if ($object->isNew()) $object->setElementId($object->getElement()->getId()); } } /* Element delete method called just before SubElement delete */ public function preDelete(BaseObject $object) { // if element not null and not new... if ($object->getElement() && !$object->getElement()->isNew()) { // delete element in his table $object->getElement()->delete(); } } }
add the "ElemenBehavior" to all your subclasses (here in" project/lib/model/SubElement.php") :
sfPropelBehavior::add('SubElement', array('ElementBehavior'));
That's all ! You can test it with a code like this :
// create subElement $test = new SubElement(); // test on element methods $test->setName('test'); $test->setContent('this is the big test !'); // test also SubElement methods $test->setAuthor('mr john smith'); // save in element table AND in sub_element table ! $test->save(); // capture subElement with id 1 $test = SubElementPeer :: retrieveByPk(1); // delete element and subElement in the two tables $test->delete(); // mix criteria for both class $c = new Criteria(); $c->add(ElementPeer :: ID, 1); $c->add(SubElementPeer :: AUTHOR, 'mr john smith'); // get a list of the subElements $subElements = SubElementPeer :: doSelectJoinElement(new Criteria());
each time you add a column or a method to the element model, you need to declare it in the behavior to be handled by the subclasses.
It's a way to go, may be there is a simplier way, but this works well for me...
$sql = 'select * from ( select * from book order by weight desc limit 5 ) as T order by popularity'; $connection = Propel::getConnection(); $statement = $connection->createStatement( ); $result = $statement->executeQuery( $sql , ResultSet::FETCHMODE_NUM); return BookPeer::populateObjects( $result );
if you won´t to add a foreignkey to sf_guard_user put this on top off you schema.yml file ;)
propel: _attributes : { package: "plugins.sfGuardPlugin.lib.model" } sf_guard_user: _attributes: { phpName: sfGuardUser } id:
now you can simple add a foreignkey
propel:
tbl_user_profile:
user_id: { type: integer, primaryKey: true, foreignTable: sf_guard_user, foreignReference: id, onDelete: cascade }
or
propel:
tbl_user_profile:
sf_guard_user_id:
Propel can create Models with autoset created_at and Updated_at field, but dont include autoset for Created_by and Updated_by field, because this fields are most aplication dependent. We can set Propel to build models with autossetting Created_by and Updated_by fields (ao any other fields) extending SfObjectBuilder. In the forum message 7535 Tamcy give us a good example. Here I post a SFObjectBuilder extension class (in this example I check if using SfGuardPlugin for user Class).
<?php /* I recomend put this class out Symfony Folder. * If you put this class in some project folder * you can use include_once 'symfony.addon.propel.builder.SfObjectBuilder.php' require_once 'sfObjectBuilder.php'; * @author Boris Duin */ class SfObjectAdvBuilder extends SfObjectBuilder { */Extend Method addSave protected function addSave(&$script) { $tmp = ''; parent::addSave($tmp); $date_script = ''; $user_updated = false; $user_created = false; foreach ($this->getTable()->getColumns() as $col) { $clo = strtolower($col->getName()); if (!$user_created && $clo == 'created_by') { $user_created = true; $date_script .= " if (\$this->isNew() && !\$this->isColumnModified('created_by')) { \$user = sfContext::getInstance()->getUser(); if (\$user instanceof sfGuardSecurityUser) \$this->setCreatedby(\$user->getUsername()) } "; } else if (!$user_updated && $clo == 'updated_by') { $user_updated = true; $date_script .= " if (\$this->isModified() && !\$this->isColumnModified('updated_by')) { \$user = sfContext::getInstance()->getUser(); if (\$user instanceof sfGuardSecurityUser) \$this->setUpdatedby(\$user->getUsername()) } "; } } $tmp = preg_replace('/{/', '{'.$date_script, $tmp, 1); $script .= $tmp; } }
Note: I write this class for synfony 0.9.x versión. Yesterday I was refactoring this class for 1.0.x version, but I leave this in my house, :(. To set propel to use this class you must edit config/propel.ini. Replace this line
for
Example: If you put this class in your Project/Lib folder you can set the line:
Now, when you run symfony propel-build-model, propel will use this class and add autoset code for created_by and Updated_by field. Here an example of models class generated by propel:
public function save($con = null) { if ($this->isNew() && !$this->isColumnModified('created_by')) { $user = sfContext::getInstance()->getUser(); if ($user instanceof sfGuardSecurityUser) $this->setCreatedby($user->getUsername()); } if ($this->isNew() && !$this->isColumnModified('created_at')) { $this->setCreatedAt(time()); } if ($this->isModified() && !$this->isColumnModified('updated_by')) { $user = sfContext::getInstance()->getUser(); if ($user instanceof sfGuardSecurityUser) $this->setUpdatedby($user->getUsername()); } if ($this->isModified() && !$this->isColumnModified('updated_at')) { $this->setUpdatedAt(time()); }
complement complex SQL in SYMFONY:
Example 1: SQL to be implemented:
SELECT b.id FROM article_mark a RIGHT JOIN article b ON a.article_id = b.id ORDER BY a.mark DESC,b.CREATED_AT DESC
Symfony implementation:
$c=new Criteria(); $c->addAlias('a', 'article_mark'); //!!!if not using alias of table, the generated sql is not correct $c->addAlias('b', 'article'); $c->addSelectColumn('b.id'); $c->addSelectColumn('a.article_id'); //!!!if one table has no column added, there's no table name after FROM clause;; actually this column is not what I need $c->addDescendingOrderByColumn('a.mark'); $c->addDescendingOrderByColumn('b.CREATED_AT'); $c->addJoin('a.ARTICLE_ID','b.ID','RIGHT JOIN'); $art_marks=ArticlePeer::doSelectRS($c); //!!! doSelect or doSelectOne can't be used
By this way, $art_marks is a MySQL recordset, using $art_marks[0] get value of column b.id;
Example 2: SQL to be implemented:
select SUM(score) from bury group by article_id having article_id=@ARTICLE_ID
Symfony implementation:
$c=new Criteria(); $c->addSelectColumn('SUM(score) as A'); //actually 'as A' has no use $c->addSelectColumn(BuryPeer::SCORE); //!! without this, no table name in generated sql; actually this column is not what I need $c->addGroupByColumn('article_id'); $crit=$c->getNewCriterion(BuryPeer::ARTICLE_ID,$article->getId()); $c->addHaving($crit); $buries=BuryPeer::doSelectRS($c); //only MySQL recordset can be used
if you using multiple database from Propel, It can be solve by writing two or more schema files.
PROJECT_DIR/config/databases.yml
all:
database1:
class: sfPropelDatabase
param:
dsn: pgsql://foo:bar@hostname/database1
database2:
class: sfPropelDatabase
param:
dsn: mysql://foo:bar@hostname/database2
PROJECT_DIR/config/database1.schema.xml
<?xml version="1.0" encoding="UTF-8"?> <database name="database1" defaultIdMethod="native" noxsd="true"> <table name="foo" phpName="Foo"> .... </table> </database>
PROJECT_DIR/config/database2.schema.xml
<?xml version="1.0" encoding="UTF-8"?> <database name="database2" defaultIdMethod="native" noxsd="true"> <table name="bar" phpName="Bar"> .... </table> </database>
Last, build model command.
$ symfony propel-build-model
Build complete.
Example, getting multiple databases connection handler.
$database1_connection_handler = Propel::getConnection(FooPeer::DATABASE_NAME); $database2_connection_handler = Propel::getConnection(BarPeer::DATABASE_NAME);