The way I do such things (querying records etc) is extending the Phalcon model and using that base model for all my models. In that base model I have created a few functions that help me do what I need. Examples below
// Base model
namespace NDN;
use \Phalcon\DI\FactoryDefault as PhDi;
use \Phalcon\Mvc\Model as PhModel;
use \Phalcon\Mvc\Model\Resultset as PhResultset;
use \Phalcon\Paginator\Adapter\QueryBuilder as PhPaginator;
class Model extends PhModel
{
public function initialize()
{
// Skip attributes here if needed - common for all models
$this->skipAttributes(
[
$this->getPrefix('created_id'),
$this->getPrefix('updated_id'),
$this->getPrefix('delete_flag'),
]
);
}
public function getOne($parameters = null, $deleted = false)
{
$parameters = $this->processDeleted($deleted, $parameters);
return self::findFirst($parameters);
}
public function getMany($parameters = null, $deleted = false)
{
$parameters = $this->processDeleted($deleted, $parameters);
return self::find($parameters);
}
public function getCount($parameters = null, $deleted = false)
{
$parameters = $this->processDeleted($deleted, $parameters);
return self::count($parameters);
}
/**
* Returns the DI container
*/
public function getDI()
{
return PhDi::getDefault();
}
/**
* Returns the Model Mapper
*/
public function getMapper()
{
return $this->getDi()->get('modelmapper');
}
private function processDeleted($deleted, $parameters)
{
if ($deleted) {
if (isset($parameters['conditions'])) {
$parameters['conditions'] = $parameters['conditions']
. " AND delete_flag = :deleted:"
} else {
$parameters['conditions'] = " delete_flag = :deleted:"
}
$parameters['bind']['deleted'] = 1;
}
return $parameters;
}
}
After that each model is defined as:
class Users extends \NDN\Model
and the getOne
, getMany
, getCount
functions are available for me to use. With my approach, I always filter out for deleted records and all my models have the delete_flag in them so there is no collision there. Your case will differ of course at which point you will have to rethink the common areas of your model and refactor them so as to remain DRY.
In a controller then I can do:
$parameters['conditions'] = 'site_id = :site_id:';
$parameters['bind']['site_id'] = 4;
$user = new User();
$results = $user->getOne($parameters);