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 with static data (without connect to db)

Hello!

Is it possible to do something like:

class ModelA
{
    public $data = [
        1 => [ 'Element 1' ],
        2 => [ 'Element 2' ],
        3 => [ 'Element 3' ],
    ];
}

class ModelB extends Phalcon\Mvc\Model
{
    public function getSource()
    {
        return 'db_table';
    }

    public function initialize()
    {
        $this->hasOne('model_a_id', 'ModelA', 'id', [
            'alias' => 'modelA'
        ]);
    }
}

$modelB = ModelB::findFirstById(1);

echo $modelB->modelA->name; // Element 1 if db_table.model_a_id = 1
echo $modelB->modelA->name; // Element 3 if db_table.model_a_id = 3

Not exactly the same (notice the different alias name), but I think this is the closest to what you're looking for:

    public function initialize()
    {
        $this->hasOne('model_a_id', 'ModelA', 'id', [
            'alias' => 'modelA1',
            'params' => [
                'conditions' => 'ModelA.id = 1'
            ]
        ]);
        $this->hasOne('model_a_id', 'ModelA', 'id', [
            'alias' => 'modelA2',
            'params' => [
                'conditions' => 'ModelA.id = 3'
            ]
        ]);
    }


42.1k

I'm not sure that's what I need. My model ModelA does not work with the database

Not exactly the same (notice the different alias name), but I think this is the closest to what you're looking for:

   public function initialize()
   {
       $this->hasOne('model_a_id', 'ModelA', 'id', [
           'alias' => 'modelA1',
          'params' => [
              'conditions' => 'ModelA.id = 1'
          ]
       ]);
       $this->hasOne('model_a_id', 'ModelA', 'id', [
           'alias' => 'modelA2',
          'params' => [
              'conditions' => 'ModelA.id = 3'
          ]
       ]);
   }


77.7k
Accepted
answer

Then why use models at all? They were designed to abstract away the DB...

But, you could go for overriding __get like so:

class ModelB extends Phalcon\Mvc\Model
{
    public function __get($name)
    {
        if($name == 'ModelA') {
            // do you own logic
            return 'something';
        }
        return parent::__get($name);
    }
}