80 likes | 191 Views
Models in Symfony. Sayed Ahmed B.Sc. Eng. in Computer Science & Engineering M. Sc. in Computer Science Exploring Computing for 14+ years sayed@justetc.net http://sayed.justetc.net. The Doctrine Query Object. Get all data from a table
E N D
Models in Symfony Sayed Ahmed B.Sc. Eng. in Computer Science & Engineering M. Sc. in Computer Science Exploring Computing for 14+ years sayed@justetc.net http://sayed.justetc.net
The Doctrine Query Object • Get all data from a table • $this->jobeet_jobs = Doctrine::getTable('JobeetJob') ->createQuery('a') ->execute(); • Get data based on conditions • $q = Doctrine_Query::create() ->from('JobeetJob j') ->where('j.created_at > ?', date('Y-m-d H:i:s', time() - 86400 * 30));
Debugging Doctrine generated SQL • You can see the complete SQLs as generated by Symfony in the /log directories • Such as frontend_dev.log • Doctrine generates prepared statements • The use of prepared statements dramatically reduces • your exposure to SQL injectionattacks • You can also check the SQL statements • using Symfonyweb debug toolbar
Object Serialization • When you need to do something automatically • before a Doctrine object is serialized to the database • you can override the save() method of the model class • isNew() method • returns true • when the object has not been serialized yet • public function save(Doctrine_Connection $conn = null) { • if ($this->isNew() && !$this->getExpiresAt()) { • $now = $this->getCreatedAt() ? $this->getDateTimeObject('created_at')->format('U') : time(); $this->setExpiresAt(date('Y-m-d H:i:s', $now + 86400 * 30)); • } • return parent::save($conn); • }
Custom Configuration • The Symfonyframework provides • a built-in configuration file for application specific settings • the app.yml file. • This YAML file can contain any setting you want: • Example File • # apps/frontend/config/app.yml • all: • active_days: 30 • From the application, the config variables can be retrieved as follows • sfConfig::get('app_active_days')
Refactoring • The logic needs to be moved to model • The controller just needs to maintain the flow • Example • $this->jobeet_jobs = Doctrine_Core::getTable('JobeetJob')->getActiveJobs();
Limit the Results • $q = Doctrine_Query::create() ->from('JobeetJob j') ->where('j.category_id = ?', $this->getId()) ->limit($max);
Dynamic Fixtures • YAML files in Symfonycan contain • PHP code that will be evaluated just before the parsing of the file • The YAML parser won't like you • if you mess up with Indentation. • Keep in mind the following simple tips when adding PHP code to a YAML file: • The <?php ?> statements must always start the line or be embedded in a value • If a <?php ?> statement ends a line, you need to explicitly output a new line ("\n")