tags:

views:

29

answers:

1

According to the Doctrine manual I should be able to reference an attribute of a model using either arrow notation ($record->myField) or array notation ($record['myField']) as long as the model is derived from the Record class.

I used Doctrine to generate my models from my database, so I have a (generated) Recipe class which extends a BaseRecipe class which extends Doctrine_Record. After instantiating a Recipe object I can use the array notation to access its values, but using arrow notation just returns empty values. What am I missing?

The BaseRecipe class which was generated by Doctrine has two methods:

public function setTableDefinition()
{
    $this->setTableName('rcp_recipe');
    $this->hasColumn('recipe_id', 'integer', 4, array(
         'type' => 'integer',
         'fixed' => 0,
         'unsigned' => false,
         'primary' => true,
         'autoincrement' => true,
         'length' => '4',
         ));
    ...
}

public function setUp()
{
    parent::setUp();
    $this->hasMany('RcpTime', array(
         'local' => 'time_id',
         'foreign' => 'time_id'));
    ...
}

And here's how I'm trying to use it:

    $newRecipes = RecipeService::getLatestRecipes();
    foreach ($newRecipes as $recipe)
    {
        echo($recipe['title']); // prints the expected value
        echo($recipe->title); // prints empty string
    }

And here's my getLatestRecipes method:

static function getLatestRecipes() {
    $q = Doctrine_Query::create()
        ->from('Recipe')
        ->orderBy('recipe_id desc')
        ->limit(5);

    return $q->fetchArray();
}
+2  A: 
return $q->fetchArray();

There's the problem ;)

Change that to

static function getLatestRecipes() {
    $q = Doctrine_Query::create()
        ->from('Recipe')
        ->orderBy('recipe_id desc')
        ->limit(5);

    return $q->execute();
}

And you will get an object, which enables you to use 'the arrow'.

You use [] to get properties from an array, and you use -> to get properties from an object. Since your method returns an array the -> doesn't work.

You should have gotten an error message though. ("Trying to get property from non-Object" or something like that)

Set error_reporting(E_ALL) while you are still developing.

tilman
That did the trick, thanks for the correct answer and the good explanation!
BenV
If you just want the actual data of that query, I would suggest to use array hydration http://www.doctrine-project.org/projects/orm/1.2/docs/manual/data-hydrators/hu#core-hydration-methods:array
tilman