Category: Models & ORM

Q: What is the best way to load Models in Controller, Cakephp 2?

I would like to ask you all how to speed up/load models in the best way? Take my contacts controller for example:

<?php

App::uses('AppController', 'Controller');
App::uses('Sanitize', 'Utility');  

class ContactController extends AppController {

/**
 * This controller does not use a model
 *
 * @var array
 */
    public $name = 'Contact';  
 
	public $uses = array('Contact', 
            'LogsContactEdit', 
            'Deal', 
            'ListIndustry', 
            'ListCountry', 
            'ListLeadOrigin', 
            'Team', 
            'ContactGoogle', 
            'LogsContactVisit', 
            'LogsContact', 
            'DealStream', 
            'ContactStream', 
            'Reminder', 
            'MessageEmailContact', 
            'User', 
            'Transaction', 
            'EmailCampaign', 
            'Order'
        );
    
    public $components = array('Stream', 'FileUploader' => array('extensions' => array('jpeg','gif','bmp','jpg','png'), 'sizeLimit' => 5242880), 'ImageUploader', 'ActivityC');
    
    public $helpers = array();
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('profile',
                           'edit');
        
        $this->Security->validatePost = false;
        $this->Security->csrfCheck = false;
        $this->Security->blackHoleCallback = 'forceSSL';
        $this->Security->requireSecure();
    }  

In total 18 Models are loaded in this controller, so my questions are:

  1. I do not want to load all models at a time, is there a way to load particular one in action. (user model that you really need)
  2. How much memory does $this->uses(); swallow on controller load?
  3. And how to speed up this process.

Thanks all!

memory models
1 Answers

Version: 2.8

user
Harper

5

1. I do not want to load all models at a time, is there a way to load particular one in action. (user model that you really need)

$this->loadModel('Model');

2. How much memory does $this->uses(); swallow on controller load?

You should use loadModel to load specified models in your controller (or in your action). This is good since you don't have to load unnecessary models at the first place. 

Muller
Muller

2

Created: 30 Sep '16

Last Reply: 6 Oct '16

Replies: 1

Views: 477

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions