天天看点

CakePHP中加载其它类的三种方法比较

在CakePHP中,如果你想调用其它与本Model或Controller不相关的类,主要有三种方法:

App::import()     ClassRegistry::init()   Controller::loadModel()

这三种方法有什么区别呢?

Posting for, someone searched for terms “cakephp what is the difference between app:import model and loadmodel” and “cakephp what is the difference between app:import and loadmodel” and landed on my blog page but unfortunately i could not provide the answer that time, perhaps. I hope it helps future visitors with similar queries.

Okay, here is the difference. Although the differences has been listed at CakePHP cookbook at cakephp.org here already but i shall try to explain them with the help of short examples.

App::import()

App::import() only includes the file. It does something like we do in include (‘./myfile.php’) and it leaves the rest on you. You can further create an object or use function/methods according to your needs. For example, when you do App::import(‘model’, ‘User’) it includes theuser.php model class file and then you do $User = new User() to create an instance of classUser which is found in user.php file. As an another example, you do App::import(‘helper’, ‘Time’) and it includes helper class file time.php and you do $time = new TimeHelper() to create an instance of TimeHelper class which is found in time.php file. The first argumentpassed to import method is the identification mark for the CakePHP internals and is used to identify the location of the requested file. In this example the string ‘model‘ or ‘helper‘ helps it to search the asked file within ‘models‘ or ‘views/helpers‘ directories respectively.

ClassRegistry::init()

ClassRegistry::init() loads the file and adds the instance to an object map and returns the instance. This is an easy and convenient way to access models. It is helpful when you need the model object to be used one time. For example, you can do ClassRegistry::init(“User”)->find(“all”) and forget about the model User further.

Controller::loadModel()

You can use Controller::loadModel() inside your controller actions for multiple use. It is the mostly used and convenient way and of course the most preferred way to include models. It includes the model class file and adds the model instance as a property of the current controller. For example, you are in PostsController and you do $this->loadModel(‘User’) so now you have User object added as $this->User automatically in the scope following this very line which you can use until your controller script processing ends.

Listing them priority-wise one would suggest you to use them in reverse order i.e. from the most preferred to the least preferred like this:

Controller::loadModel()

ClassRegistry::init()

App::import()

And now perhaps you know why. Do you?

上面是英文,你要是看不懂,直接看我的代码:(演示在Task控制器类中调用类User)

<?php

class TasksController extends AppController {

var $name = 'Tasks';

function index()

{

$this->set('tasks',$this->Task->find('all'));

}

}

?>

注意上面代码中引用其它类时的加红的单引号和双引号,

继续阅读