Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to load models in CakePHP?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 120
    Comment on it

    I am writing this blog for them who are new to Cakephp and learning it. In Cakephp there are three ways to load models:

    First way is:

    App::import(): It will find and require()s the file and in order to use it you need to be instantiate the class. import() the type of class, the name and file path details.

    Example: If you want to load User Model then this is how you do it with App::import()

    App::import('Model', 'User');
    $this -> User = new User();

     

    Now second way of loading model is by:

    ClassRegistry::init(): It will load the file. It adds the instance to the object map and returns the instance. This is the better way to load Model.

    Example: Following code will load User Model and find all the users
     

    $this->User = ClassRegistry::init('User');
    $this->User->find('all');

     

    Third way of loading Model is:

    Controller::LoadModel(): It uses ClassRegistry::init() as well as adds the Model as a property of the controller. For model caching it allows $persistModel. This method only works in Controller and it is one of the best way to load model. Below is the example will show you how to load model from this method

    $this->loadModel('User');

    Note: In a Controller if you are using one or two models to load multiple times in every action, then in this case best way is to use:

    public $uses = array('Model1', 'Model2');

     

    Thanks for reading the blog.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: