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'
]
//...
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 [];
}
}
modelsManager
key in DI container.
EventsManager
service to newly created MySQL adapter instance. Otherwise, you will not be able to collect database queries information.
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';
}
}
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.