First beta of Phalcon 1.0.0

    Today, the Phalcon development team released the first beta version of the Phalcon 1.0.0 framework. For those who are not in the know: Phalcon is a PHP framework written in C and working as an extension for PHP, you can read about it in Habré in articles Phalcon - compiled PHP MVC Framework and Phalcon: Let's learn by example .
    The purpose of this release is to get feedback from the community and detect maximum bugs.



    A brief announcement of the important innovations of this version:
    1. Tiered caching
    2. Improvements to the Volt template engine
    3. Horizontal and vertical sharding
    4. Record Snapshots
    5. Dynamic update
    6. Validation



    1. Multilevel caching


    A new feature of the caching component allows the developer to implement the cache in several levels. The feature will be useful when storing the cache in several places (caching systems) with different lifetimes, and subsequent subsequent reading from them, starting from the fastest (in the order of registration) and ending with the slowest, until the lifetime in all of them expires.
     3600
    ));
    $fastFrontend = new Phalcon\Cache\Frontend\Data(array(
        "lifetime" => 86400
    ));
    $slowFrontend = new Phalcon\Cache\Frontend\Data(array(
        "lifetime" => 604800
    ));
    //Backends are registered from the fastest to the slower
    $cache = new \Phalcon\Cache\Multiple(array(
      new Phalcon\Cache\Backend\Apc($frontCache, array(
            "prefix" => 'cache',
        )),
        new Phalcon\Cache\Backend\Memcache($fastFrontCache, array(
            "prefix" => 'cache',
            "host" => "localhost",
            "port" => "11211"
        )),
        new Phalcon\Cache\Backend\File($slowestFrontCache, array(
            "prefix" => 'cache',
            "cacheDir" => "../app/cache/"
        ));
    ));
    // Сохранение, сохраняется сразу во все системы кеширования
    $cache->save('my-key', $data);
    // Получение, читается сразу со всех систем где кеш еще живой
    $data = $cache->get('my-key');
    



    2. Improvements in the Volt template engine


    Volt (also written in C) received several new features in this version:
    {# Тернарный оператор #}
    {{ total > 0 ? total|format('%0.2f') : '0.0' }}
    {# Поддержка For-Else #}
    {% for robot in robots %}
        {{ robot.name }}
    {% else %}
        There are no robots
    {% endfor %}
    {# Циклы внутри контекста #}
    
    {% for robot in robots %}
        {% if loop.first %}
            ae
            
        {% endif %}
        
        {% if loop.last %}
            
        {% endif %}
    {% endfor %}
    
    PositionIdName
    {{ loop.index }}{{ robot.id }}{{ robot.name }}
    {# Контролирование пробелов в разделении (Space control delimiters) #}
      {%- for robot in robots -%}
    • {{- robot.name -}}
    • {%- endfor %}



    3. Horizontal and vertical sharding


    Now you can use different connections to write and read from the database. Usefulness is shown when working with the master / slave DBMS configuration:
    class Robots extends Phalcon\Mvc\Model
    {
        public function initialize()
        {
            $this->setReadConnectionService('dbSlave');
            $this->setWriteConnectionService('dbMaster');
        }
    }
    


    Horizontal sharding is also possible when the connection is selected depending on the requested data:
    class Robots extends Phalcon\Mvc\Model
    {
        public function selectReadConnection($intermediate, $bindParams, $bindTypes)
        {
            // Проверяем, есть ли в запросе условие 'where'
            if (isset($intermediate['where'])) {
                $conditions = $intermediate['where'];
                // Выбираем соединение в зависимости по требуемому условия
                if ($conditions['left']['name'] == 'id') {
                    $id = $conditions['right']['value'];
                    if ($id > 0 && $id < 10000) {
                        return $this->getDI()->get('dbShard1');
                    }
                    if ($id > 10000) {
                        return $this->getDI()->get('dbShard2');
                    }
                }
            }
            // В остальных случаях используем соединение по умолчанию
            return $this->getDI()->get('dbShard0');
        }
    }
    



    4. Record Snapshots


    Now models can set a property for storing field values ​​at the time of the request. You can use this function to audit or verify changes in field values ​​in the process:
    class Robots extends Phalcon\Mvc\Model
    {
        public function initalize()
        {
            $this->keepSnapshots(true);
        }
    }
    


    So you can check the values ​​of which fields have been changed:
    $robot = new Robots();
    $robot->name = 'Other name';
    var_dump($robot->getChangedFields()); // ['name']
    var_dump($robot->hasChanged('name')); // true
    var_dump($robot->hasChanged('type')); // false
    



    5. Dynamic update


    Allows ORM to use only those fields whose values ​​have been changed when generating an UPDATE SQL query, and not to collect all fields and all their values. This reduces traffic between the application and database servers, which in turn can have a beneficial effect on performance:
    class Robots extends Phalcon\Mvc\Model
    {
        public function initalize()
        {
            $this->useDynamicUpdate(true);
        }
    }
    



    6. Validation


    The new Phalcon \ Validation component allows independent data verification. The component is based on checks already implemented in ORM and ODM. With it, you can check data that is not associated with any model or collection:

    $validation = new Phalcon\Validation();
    $validation
        ->add('name', new PresenceOf(array(
            'message' => 'Поле name обязательно для заполнения'
        )))
        ->add('name', new StringLength(array(
            'min' => 5,
            'minimumMessage' => 'Значение поля name слишком короткое'
        )))
        ->add('email', new PresenceOf(array(
            'message' => 'Поле email обязательно для заполнения '
        )))
        ->add('email', new Email(array(
            'message' => 'Email не соответствует формату'
        )))
        ->add('login', new PresenceOf(array(
            'message' => 'Поле login обязательно для заполнения'
        )));
    $messages = $validation->validate($_POST);
    if (count($messages)) {
        foreach ($messages as $message) {
            echo $message;
        }
    } 
    


    This release also contains other improvements and corrections, you can find out all of them by reading the full list of changes or in Russian in the Russian Phalcon support group on VKontakte.

    Help with testing


    You can get this version with GitHub from the 1.0.0 branch:

    git clone http://github.com/phalcon/cphalcon
    cd build
    git checkout 1.0.0
    sudo ./install
    


    Windows users can download the finished DLL from the download page.

    We will gladly accept your comments and suggestions on Phosphorum , Stack Overflow or Google Group . If you find an error and can form a test to repeat it or solve it, send us a pull request or create an issue on GitHub .

    PS Free translation with additions, the original is here .
    To support the framework, a VKontakte group was created , a Russian site, and documentation localization started , join!
    There is also another translation of documentation and examples.Phalcon PHP FrameWork

    Original photo copyright Simon Roy: 500px.com/photo/7924712

    Also popular now: