Working with database in Phalcon post

11/23/2014 with tags : php, phalcon

Phalcon introoduces 3 abstraction layers for working with database

Assume we have defined class named Robots, then to get all robots satisfying given conditions we write

Robots::find(array(
    "conditions" => "(type = 'virtual') AND ( year > '1952')",
    "order" => "name"
));

Or using \Phalcon\Mvc\Model\Criteria class for an object oriented notations

Robots::query()
    ->where("type = 'virtual'")
    ->andWhere("year > '1952'")
    ->orderBy("name")
    ->execute();

When code execution reaches execute() method in example above, this is what Phalcon does

  1. Method is executed on instance of \Phalcon\Mvc\Model\Criteria class, cretated by model Robots

        $criteria = new \Phalcon\Mvc\Model\Criteria();
        $criteria->setModelName('Robots');
    

    see on github

  2. all coditions are gathered and passed to Robots::find method (like in first code example)

        $params = $criteria->getParams();
        Robots::find($params);
    

    see on github

  3. model creates new \Phalcon\Mvc\Model\Query\Builder instance and passes all given parameters to build a PHQL query string. In fact it calls getQuery method to get \Phalcon\Mvc\Model\Query object

        $builder = new \Phalcon\Mvc\Model\Query\Builder($params);
        $builder->from('Robots');
        $query = $builder->getQuery();
        $query->execute();
    

    see on github

  4. Inside a getQuery method PHQL query string is created by calling getPhql. This PHQL is then passed to newly created \Phalcon\Mvc\Model\Query instance

        // QueryBuilder::getQuery method
        $phql = $builder->getPhql();
        $query = new \Phalcon\Mvc\Model\Query($phql);
    

    see on github

  5. \Phalcon\Mvc\Model\Query then parses given PHQL string to build an intermediate representation (IR) and executes it. In case of selecting data _executeSelect is called.

        // Query::execute() method 
        $query->parse();
        $query->_executeSelect(); // executes select using PHQL IR 
    

    see on github

  6. Finally query is executed using underlying database adapter service. Adapter is provided by Model::getReadConnection method

    see on github