views:

29

answers:

2

Hello! I'd like to encapsulate functionality specific to certain models by including methods in the model class definitions. So, for example:

abstract class BaseUser extends DoctrineRecord {    

    public function setTableDefinition(){  
       //etc.  
    }  

    public function setUp(){  
       //etc.  
    } 

    public function getName(){  
       return $this->name  
    }
}

$this->name throws an error, as does $name. Is it possible to access the model properties from here?

A: 

The Basexxx classes are abstract. You should add your method to the User class which extends BaseUser.

[Edit] You can access properties of the base class in your child class using $this->property. For example:

class User extends BaseUser {
   public function getWelcomeString() {
      return 'Welcome, ' . $this->name . '!';
   }
}

You can then access your custom functions in addition to all the base class properties from an instance of your chilod class:

$user = new User();
//Hydrate object from database
echo $user->getWelcomeString();     // implemented in your child class
echo 'Your name is ' . $user->name; // implemented in the base class
BenV
You're right - thank you. Do you know how I can access the model properties from these functions? Thanks for the help.
Justin
@Justin: I've updated my answer with an example. Since you're new to SO I'll remind you to accept the best answer by clicking the checkmark to the left of the answer.
BenV
Thanks again. Unfortunately, that's exactly what I've been trying, but an error is thrown that reads: "Undefined property: User::$name".But I'm definitely defining the column correctly, because $user->name is returning as expected. It's just $user->getName() that's throwing the error.
Justin
Sorry, the "Undefined::Property" was an interpreter warning, not an error. Nonetheless, it wasn't working due to a naming conflict (see below).
Justin
A: 

Properties can be accessed using $this->propertyName as anyone would expect. My problem was that getProperty (getName in my example) is a function that the Doctrine framework automatically creates, creating a conflict when I tried to create my own. I changed the name to whatIsName() and everything worked.

Justin