Extending sfDoctrineRecord in symfony

人盡茶涼 提交于 2019-12-07 16:57:36

问题


I've added some functionality to some of my instance classes in my symfony project that I want ALL of my instance classes to have. If I didn't have any qualms about editing the core symfony installation, I would just add my methods directly to the sfDoctrineRecord class. But I don't want to do that, of course, because my changes would break on upgrade, plus my changes wouldn't port well to other projects.

If I want to add certain functionality to all my instance classes in symfony, what's the "right" way to do that?

(P.S. When I say "instance class", I mean something like lib/model/doctrine/Customer.class.php.)


回答1:


Steps:

  1. Create myDoctrineRecord

    abstract class myDoctrineRecord extends sfDoctrineRecord
    {
      public function commonRecordMethod() { }
    }
    

    I place this file in lib/record, but you can put it anywhere that the autoloader will see it.

  2. Set Symfony to use this class in the configureDoctrine callback of your ProjectConfiguration:

     public function configureDoctrine(Doctrine_Manager $manager)
     {
       sfConfig::set('doctrine_model_builder_options', array('baseClassName' => 'myDoctrineRecord'));
     }
    

That's it! Isn't Symfony great? :)




回答2:


I suppose the proper way would probably be to add a Doctrine_Template to the models in question, however you would need to define it as a behavior for every model in your schema.yml

class MyMethodsTemplate extends Doctrine_Template
{
   public function customMethod1(){
      $model = $this->getInvoker();
      //do stuff with model
   }

   public function customMethod2(){
      $model = $this->getInvoker();
      //do stuff with model
   }
}

And then in your schema.yml:

ModelName:
  actAs:
   MyMethodTemplate: ~
  # the rest of your definition

After you rebuild you should be able to call:

$model = new ModelName();
$model->customMethod1();
$model->customMethod2(); 

Of course Doctrine templates and listeners are much more powerful than that. You should take a look at the documentation for decent overview



来源:https://stackoverflow.com/questions/4391483/extending-sfdoctrinerecord-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!