开发者

Writing model methods in Doctrine

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->na开发者_运维百科me throws an error, as does $name. Is it possible to access the model properties from here?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜