CakePHP: 性能方面的考虑

    技术2022-05-20  57

    1、$uses和loadModel的使用

    在CakePHP1.3.x版本中尽量不使用$uses, 因为这会全部加载使用到的model,占用内存和消耗不必要的时间。

    相反在需要使用model的地方,使用loadModel加载它。在不需要关联数据的情况下,设置其recursive属性为-1。

     

    另外控制器默认的数据模型不用加载,如果users_controller不用调用loadModel('User'),User模型及其关联模型会自动加载,

    在控制器中只要直接使用即可:

            $this->User...     ;  

            $this->User->Role...

     

    使用lazy loading技术, 1.3版本有一个lazy_model,把你的app_model的基类换成LazyModel,

    将使得model仅在实际调用的地方才会真正加载。

     

    2、eval和requestAction的使用

    尽量不要使用eval和requestAction。eval会导致新的脚本解析进程,而requestAction等同于发出一个新的请求。

    eval可以用{}或$$类似语法替换,如

    case 1       

    $this->{$this->modelClass}->hasField("country_id");

    -----------------------------------------------------------------

    case 2

    $foo = 'city';

    $$foo = 'shanghai';

     

    requestAction用view/helper替换

     

    3、Cache

    需要分布式数据共享的地方用memcached,本地数据尽量用Apc。在使用到Cache::write/read的地方通过参数指定使用core.php中配置的哪个Cache。

    4. do not use config::load, instead use include_once() as long as you know the file name and must be therethe file_exist() check takes much time.

    5. never put loadModel or ClassRegistry::init in a loop, these functions take much time

    6. when request deals/*, it also loaded all associated models even you have set $this->Deal->recursive to -1; remember this, if you in all cases didn't need to retrieve associated tables' data, just remove association from the model.

    7. when request deals/*, it also setup all routes for all plugins, admin/*, so you need to cut down your plugins as less as possible.

    8. optimize static mapping codes:Router::mapResources('deals');Router::mapResources('vendors');Router::mapResources('users');to dynamically mapping    if(isset($uri_first) && $uri_first != 'admin') {        Router::mapResources(strtolower($uri_first));    }        6. load components on the fly rather than put it in $components

    7. load model on the fly rather than put it in $used

    8. cake loaded all common libs at cake/libs directory even it is not used in configure.php->App::import->App::_find,

    so a better way is to overwrite the pre-loading to lazy loading.


    最新回复(0)