MySQL database

Setup connection

Before we start using MySQL in our project, we have to setup connection details, by adding them to app/config/config.php file:


//...
'db' => [
    'host'      => 'localhost',
    'port'      => 3306, 
    'username'  => 'USERNAME',
    'password'  => 'PASSWORD',
    'dbname'    => 'test',
    'charset'   => 'utf8'
]
//...

Create provider

To make MySQL available in the application, you have to create a service provider


use Phalcon\DiInterface;
use Vegas\DI\ServiceProviderInterface;

/**
 * Class MysqlServiceProvider
 */
class MysqlServiceProvider implements ServiceProviderInterface
{
    const SERVICE_NAME = 'db';

    /**
     * {@inheritdoc}
     */
    public function register(DiInterface $di)
    {
        $di->set(self::SERVICE_NAME, function() use ($di) {
            $arrayConfig = $di->get('config')->{self::SERVICE_NAME};
            $db = new \Phalcon\Db\Adapter\Pdo\Mysql($arrayConfig);
            $db->setEventsManager($di->getShared('eventsManager')); // @see profiling section
            return $db;
        }, true);
    }

    /**
     * {@inheritdoc}
     */
    public function getDependencies()
    {
        return [];
    }
}

Note that after MySQL initialization, a ModelsManager used for data manipulation will be registered automatically under modelsManager key in DI container.
When you're going to use Vegas Profiler you must attach EventsManager service to newly created MySQL adapter instance. Otherwise, you will not be able to collect database queries information.

Create model

Once we have a MySQL setup in application, we can start creating a data-models.
Create a file Foo.php in the models directory in one module.


namespace Foo\Models;

use Vegas\Db\Decorator\ModelAbstract;

class Foo extends ModelAbstract
{
    public $id;
    public $slug;
    public $created_at;
    public $updated_at;
    // Specify all attributes here
    
    /**
     * Returns the name of MySQL table name
     */
    public function getSource()
    {
        return 'foo_table';
    }
}

According to Phalcon manual:
If you’re using PHP 5.4/5.5 it is recommended you declare each column that makes part of the model in order to save memory and reduce the memory allocation.
therefore we suggest more verbose way of implementing MySQL models.

For more information about ORM check the following link.