From my current multi-module app
/**
* Class ArticleRepository
*
* @package Suzuki\Module\News\Repository
*/
class ArticleRepository extends AbstractRepository
{
/**
* @param $parameters
* @return Article|Row
*/
public function findFirst($parameters = null)
{
return Article::findFirst($parameters);
}
/**
* @param $parameters
* @return \Phalcon\Mvc\Model\ResultsetInterface|Article[]
*/
public function find($parameters = null)
{
return Article::find($parameters);
}
/**
* @param $adminId
* @return ResultsetInterface
*/
public function findByAdminId($adminId)
{
return $this->modelsManager->createBuilder()
->columns('id,title,addDate')
->from(['Article' => 'N:Article'])
->where('adminId = :adminId:', ['adminId' => $adminId])
->getQuery()
->execute();
}
/**
* @param $limit
* @param $offset
* @param $handledParams
* @return ResultsetInterface
*/
public function findByLimitOffsetConditions($limit, $offset, $handledParams)
{
$builder = $this->modelsManager->createBuilder()
->columns('Article.id,title,Article.addDate,adminId,Article.active,updateDate,description,firstName,lastName,
image,notify')
->from(['Article' => 'N:Article'])
->leftJoin('A:Admin', 'Article.adminId = Admin.id', 'Admin')
->orderBy('Article.id DESC');
if (!empty($handledParams)) {
$builder->where($handledParams['where'], $handledParams['bind']);
}
if (!empty($limit)) {
$builder->limit($limit, $offset);
}
return $builder->orderBy('Article.addDate DESC,Article.updateDate DESC')
->getQuery()
->execute();
}
abstract class AbstractRepository implements RepositoryInterface
{
/**
* @var Manager
*/
protected $modelsManager;
/**
* AbstractRepository constructor.
*/
public function __construct()
{
$this->modelsManager = Di::getDefault()->get('modelsManager');
}
/**
* @param $parameters
* @return mixed
*/
public abstract function findFirst($parameters = null);
/**
* @param $parameters
* @return mixed
*/
public abstract function find($parameters = null);
}
class Repositories
{
static $repositories = [];
/**
* @param string $name name provided as Modulename:Classname
* @return mixed
* @throws Exception
*/
public static function get($name)
{
$names = explode(':', $name);
$modelClassName = "Suzuki\\Module\\{$names[0]}\\Model\\{$names[1]}";
if (class_exists($modelClassName)) {
$repositoryClassName = "Suzuki\\Module\\{$names[0]}\\Repository\\{$names[1]}Repository";
if (class_exists($repositoryClassName)) {
// Check if repository was already created
if(isset(self::$repositories[$repositoryClassName])) {
return self::$repositories[$repositoryClassName];
}
$repository = new $repositoryClassName;
self::$repositories[$repositoryClassName] = $repository;
return $repository;
}
throw new Exception("Repository for model $modelClassName not found");
}
throw new Exception("Model $modelClassName was not found");
}
}