Model loader

by imhuy
This component helps you to load your models on the fly ( I mean in your actions, whenever).
If you just add the model names to $uses, Cake will autoload for you.
But when you have large controllers, you find out that you will need to use difference models in different actions. The Cake autoloading will make your application slow down and need more memory usage by loading models that you don't need (in the current action).

This component helps you to solve that problem. It gives you freedom to load the Model on the fly. You can also name the model any name you want.

This is the cod. It's simple because I just do the things that Controller::constructClasses do with some modifications.

You will save it to app/controllers/components/model_loader.php

Component Class:

<?php 
<?php

/**
 * @author Huy <www.imhuy.com>
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 */


class ModelLoaderComponent extends Object
{
    
    var 
$controller null;
    
    function 
startup(&$controller)
    {
        
$this->setController($controller);
    }
    
/**
     * Load the model and assign it to the controller
     *
     * @access public
     * @param string $modelClass
     * @return bool | mixed
     */
    
function load($modelClass$objectName null)
    {
        if (!
$this->controller)
        {
            return 
false;
        }
        
        
        
$id false;
        
$object null;
        
$cached false;
        
        
$plugin '';
        
        if (
$this->controller->plugin
        {
            
$plugin $this->controller->plugin '.';
        }
        
        if (!
class_exists($modelClass))
        {
            
loadModel($plugin $modelClass);
        }
        
        if (
class_exists($modelClass))
        {
            if (!
$objectName)
            {
                
$objectName $modelClass;
            }
            
            if (
$this->controller->persistModel)
            {
                
$cached $this->_persist($modelClassnull$object);
            }
            
            if (
false === $cached)
            {
                
$model =& new $modelClass($id);
                
$this->controller->modelNames[] = $modelClass;
                
$this->controller->{$objectName} =& $model;
                
                if (
$this->controller->persistModel === true
                {
                    
$this->_persist($modelClasstrue$model);
                    
$registry ClassRegistry::getInstance();
                    
$this->_persist($modelClass 'registry'true$registry->__objects'registry');
                }
                
            }
            else
            {
                
$this->_persist($modelClass 'registry'true$object'registry');
                
$this->_persist($modelClasstrue$object);
                
$this->controller->{$objectName} = $this->{$modelClass};
                
                
// unset the temp model, for PHP4 
                
unset($this->{$modelClass});
                
$this->controller->modelNames[] = $modelClass;
            }
        }
        else
        {
            return 
$this->controller->cakeError('missingModel', array(array('className' => $modelClass'webroot' => '''base' => $this->controller->base)));
        }
        return 
true;
    }
    
    
/**
     * Set the controller to work
     *
     * @access public
     * @param AppController $controller
     * @return void
     */
    
function setController(&$controller)
    {
        
$this->controller $controller;
    }
}
?>
?>

Usage



  class FooController extends AppController
  {
      var $components = array('ModelLoader');
      
      function index($id)
      {
          $this->ModelLoader->setController($this);
          $this->ModelLoader->load('Product');
          $this->Product->read(null, $id);
  
          $this->ModelLoader->load('Solution', 'Solu');
          $this->Solu->read(null, $id);
      }
  }

Have fun !

Report

More on Components

Advertising

Comments

  • veepee posted on 02/27/10 08:46:52 AM
    Hi,

    May i know is it possible to insert into the newly created table, i.e. in
    this example, the customer table using model?

    $this->Q->query("CREATE TABLE customer
    (First_Name char(50),
    Last_Name char(50),
    Address char(50) default 'Unknown',
    City char(50) default 'Mumbai',
    Country char(25),
    Birth_Date date)");
    }
    $this->loadModel('Customer');
    $this->Customers->saveAll(data);

    I've tried it but this does not work. May I know if this could work or I
    need to create another insert statement using

    $this->Q->query("INSERT INTO customer...");
  • asecondwill posted on 10/18/09 07:57:06 PM
    $model = ClassRegistry::init('ModelName');

    ?
  • konsumer posted on 11/11/07 06:19:12 PM
    what about:

    <?php
    loadModel
    ('Product');
    $tmpProduct = new Product();
    $tmpProduct->read(null$id); 
    ?>

    just as much code in controller, and no component needed.
  • imhuy posted on 10/13/07 01:55:41 AM
    @Steve Oliveira:
    No, this function just load the class. It does not create a new Model Object.

    @Sergey Storchay:
    thanks for your helpful comment. I will improve my component.
  • storchay posted on 09/28/07 02:09:03 AM
    function setController(&$controller)
    {
    $this->controller = $controller;
    }

    Why not function startup(&$controller)?
  • coeus posted on 09/28/07 12:31:40 AM
    Doesn't loadModel(modelName) already do this?
login to post a comment.