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

Get meta data from static function?

I'm writing a helper method to findFirst() that will work with multiple-column and non-integer keys.

To do so, I need to find the primary key columns of whatever model I'm using the function with. Currently I do this:

$class = get_called_class();
$MetaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$primary_keys = $MetaData->getPrimaryKeyAttributes(new $class());

I hate to duplicate work though, so I wonder if Phalcon already has that information somewhere that I can access?

edited Mar '14

Hi, Try this inside your model class

$primary_keys = $this->getModelsMetaData()->getPrimaryKeyAttributes($this);

Like findFirst(), my function (findFirstByKey()) is a static function, so $this doesn't exist, and getModelsMetaData() can't be called statically.

edited Mar '14

Maybe

class Robots extends \Phalcon\Mvc\Model
{
    public static function findFirstByKey()
    {
        $class = __CLASS__;
        $object = new $class();
        $primary_keys = $object->getModelsMetaData()->getPrimaryKeyAttributes( $object );
    }
}

That's functionally equivalent to the code I already posted in my first post.

My code is working - it does what I want. I was merely wondering if the work I'm doing has already been done by Phalcon by the time I call findFirstByKey(). If that data has already been retrieved and parsed by Phalcon, there's no sense me doing it again.

Yes it is the same functionality, but at this example you have only one model which you can use in your function findFirstByKey(), you doesn't need second model and created model as parameter which you can't use later Better write NFR, maybe this function you try to write could be done in final 1.3 ?

Sorry, I don't understand what you mean.

However, looking closer I do see that with yours, I don't need to make a new MetaData object.

Sorry: "you doesn't need second model" should be you doesn't need second object :)

class Robots extends \Phalcon\Mvc\Model
{
    public static function findFirstByKey()
    {
        $class = __CLASS__; //in static method get_called_class you get __CLASS__ but in non static method you get controller class name if you call your function from  for eg IndexController
        $object = new $class(); //you create object which you can use later for whatever you want, you don't need to use new object from another class
        $primary_keys = $object->getModelsMetaData()->getPrimaryKeyAttributes( $object ); // you use the same object 
    }
}

But as you said at the end functionality is the same :)

edited Oct '14

re: get_called_class() vs CLASS

My findFirstByKey() is defined in a BaseModel class that all my models extend. In this situation, calling CLASS gives me BaseModel, but get_called_class() properly gives me Robots. The rest of the code still works, I just needed to keep using get_called_class().