douao3636 2011-10-07 23:21
浏览 52
已采纳

什么是在PHP中重复使用类的最有效方法?

I have a basic MVC setup with helper classes containing utility methods, several of these are likely to be used when loading a view, in both the view itself, the controller and sometimes, but not often, the models. I use autoloading to find the helper files I need, so the class is only ever included once, then, in theory the file shouldn't get searched/included again, that way I don't have to put include statements in the script and (i believe) the file isn't loaded unless the class is used.

My question is what's likely to be the most efficient way to make calls to these helper classes? Should I make all methods in a given helper static, or maybe use a singleton pattern for the helpers or should I just create a new instance wherever it's used (e.g. an instance in the view an instance in the controller...) ?

thanks for your input

  • 写回答

1条回答 默认 最新

  • drcomwc134525 2011-10-07 23:27
    关注

    (i believe) the file isn't loaded unless the class is used.

    Correct. That's how autoloading works.

    My question is what's likely to be the most efficient way to make calls to these helper classes?

    Efficient, well, what's efficient? Maybe using C/C++ and compiling the stuff. Anyway, let's try:

    Should I make all methods in a given helper static,

    No.

    or maybe use a singleton pattern for the helpers

    No.

    or should I just create a new instance wherever it's used (e.g. an instance in the view an instance in the controller...) ?

    Yes. If you only use them from time to time, that's very efficient because you can make use of anything as you see fit.

    In case you use the same object more often, pass it around, inject it into other functions as it's needed.

    This way you will get the most benefit from autoloading.


    Helper object that can have multiple helper you can pass around even, will autoload on first access (lazy loading):

    class Helper
    {
        private $helpers = array();
        public function __get($name)
        {
            $name = strtolower($name);
            if(!isset($this->helpers[$name]))
            {
                $classname = ucfirst($name).'Helper';
                $this->helpers[$name] = new $classname;
            }
            return $this->helpers[$name];
        }
    }
    
    class Controller
    {
        private $helper;
        public function __construct()
        {
            $this->helper = new Helper();
        }
    
        public function indexAction()
        {
            $ingredients = $this->helper->something->getIngredientsList();
            ....
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU