We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Model as parameter

It's possible to create a function and send a Model Object in the parameter to make a find ? E.g

// The function
public  function findWithArray($model, $array){
    return $model::find(array(
        "id IN ({ids:array})",
        "bind" => array('ids' => $array)
    ))->toArray();
}

// The call
$var = this->findWithArray(Robots, $myArray);
$var2 = this->findWithArray(Users, $myArray);

This will not working but I want to know if there is a solution for that. If not I have to create this function in each model



93.7k
Accepted
answer

Here is a hacky solution that will work. I'm using something similar in my custom CRUD helper to generate annoying admin forms :)

$obj = new $model; // Your function param
$obj->find();

Or if your models are always in the same namespace, you could even do:

$model = 'Models\\'. $model; // Your function param
$obj = new $model;
$obj->find();

Thanks for your answer. I'm trying to use my function and send the parameter but I have this notice in the error log:

PHP Notice:  Use of undefined constant Robots - assumed 'Robots'

How can we fix that ?

edited Oct '16

You must pass Robots::class or Users::class

Also get rid of array, and use [].

Thanks guys ! It's awesome. This will help me to optimize my code

Also i recommend putting all finding stuff to seperated classes.

edited Oct '16

What do you mean ? Could you show a code snippet please ?

Also i recommend putting all finding stuff to seperated classes.

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");
    }
}