scaffold.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: scaffold_8php-source.html 580 2008-07-01 14:45:49Z gwoo $ */
00003 /**
00004  * Scaffold.
00005  *
00006  * Automatic forms and actions generation for rapid web application development.
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
00011  * Copyright 2005-2008, Cake Software Foundation, Inc.
00012  *                              1785 E. Sahara Avenue, Suite 490-204
00013  *                              Las Vegas, Nevada 89104
00014  *
00015  * Licensed under The MIT License
00016  * Redistributions of files must retain the above copyright notice.
00017  *
00018  * @filesource
00019  * @copyright       Copyright 2005-2008, Cake Software Foundation, Inc.
00020  * @link                http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00021  * @package         cake
00022  * @subpackage      cake.cake.libs.controller
00023  * @since       Cake v 0.10.0.1076
00024  * @version         $Revision: 580 $
00025  * @modifiedby      $LastChangedBy: gwoo $
00026  * @lastmodified    $Date: 2008-07-01 09:45:49 -0500 (Tue, 01 Jul 2008) $
00027  * @license         http://www.opensource.org/licenses/mit-license.php The MIT License
00028  */
00029 /**
00030  * Scaffolding is a set of automatic views, forms and controllers for starting web development work faster.
00031  *
00032  * Scaffold inspects your database tables, and making educated guesses, sets up a
00033  * number of pages for each of your Models. These pages have data forms that work,
00034  * and afford the web developer an early look at the data, and the possibility to over-ride
00035  * scaffolded actions with custom-made ones.
00036  *
00037  * @package     cake
00038  * @subpackage  cake.cake.libs.controller
00039  */
00040 class Scaffold extends Object {
00041 /**
00042  * Controller object
00043  *
00044  * @var object
00045  * @access public
00046  */
00047     var $controller = null;
00048 /**
00049  * Name of the controller to scaffold
00050  *
00051  * @var string
00052  * @access public
00053  */
00054     var $name = null;
00055 /**
00056  * Action to be performed.
00057  *
00058  * @var string
00059  * @access public
00060  */
00061     var $action = null;
00062 /**
00063  * Name of current model this view context is attached to
00064  *
00065  * @var string
00066  * @access public
00067  */
00068     var $model = null;
00069 /**
00070  * Path to View.
00071  *
00072  * @var string
00073  * @access public
00074  */
00075     var $viewPath;
00076 /**
00077  * Path parts for creating links in views.
00078  *
00079  * @var string Base URL
00080  * @access public
00081  */
00082     var $base = null;
00083 /**
00084  * Name of layout to use with this View.
00085  *
00086  * @var string
00087  * @access public
00088  */
00089     var $layout = 'default';
00090 /**
00091  * Array of parameter data
00092  *
00093  * @var array
00094  * @access public
00095  */
00096     var $params;
00097 /**
00098  * File extension. Defaults to Cake's template ".ctp".
00099  *
00100  * @var array
00101  * @access public
00102  */
00103     var $ext = '.ctp';
00104 /**
00105  * Sub-directory for this view file.
00106  *
00107  * @var string
00108  * @access public
00109  */
00110     var $subDir = null;
00111 /**
00112  * Plugin name.
00113  *
00114  * @var string
00115  * @access public
00116  */
00117     var $plugin = null;
00118 /**
00119  * List of variables to collect from the associated controller
00120  *
00121  * @var array
00122  * @access private
00123  */
00124     var $__passedVars = array('action', 'base', 'webroot', 'layout', 'name', 'viewPath', 'ext', 'params', 'data', 'plugin', 'cacheAction');
00125 /**
00126  * Title HTML element for current scaffolded view
00127  *
00128  * @var string
00129  * @access public
00130  */
00131     var $scaffoldTitle = null;
00132 /**
00133  * Construct and set up given controller with given parameters.
00134  *
00135  * @param string $controller_class Name of controller
00136  * @param array $params Parameters for scaffolding
00137  */
00138     function __construct(&$controller, $params) {
00139         $this->controller =& $controller;
00140         
00141         $count = count($this->__passedVars);
00142         for ($j = 0; $j < $count; $j++) {
00143             $var = $this->__passedVars[$j];
00144             $this->{$var} = $controller->{$var};
00145         }
00146         
00147         $this->redirect = array('action'=> 'index');
00148 
00149         if (!in_array('Form', $this->controller->helpers)) {
00150             $this->controller->helpers[] = 'Form';
00151         }
00152 
00153         if ($this->controller->constructClasses() === false) {
00154             return $this->cakeError('missingModel', array(array('className' => $this->modelKey, 'webroot' => '', 'base' => $this->controller->base)));
00155         }
00156 
00157         $class = $controller->uses[0];
00158         if (strpos($class, '.') !== false) {
00159             list($plugin, $class) = explode('.', $class);
00160         }
00161 
00162         if (!empty($controller->uses) && class_exists($class)) {
00163             $controller->modelClass = $class;
00164             $controller->modelKey = Inflector::underscore($class);
00165         }
00166         $this->modelClass = $controller->modelClass;
00167         $this->modelKey = $controller->modelKey;
00168 
00169         if (!is_object($this->controller->{$this->modelClass})) {
00170             return $this->cakeError('missingModel', array(array('className' => $this->modelClass, 'webroot' => '', 'base' => $controller->base)));
00171         }
00172         $this->ScaffoldModel =& $this->controller->{$this->modelClass};
00173         $this->scaffoldTitle = Inflector::humanize($this->viewPath);
00174         $this->scaffoldActions = $controller->scaffold;
00175         $this->controller->pageTitle = __('Scaffold :: ', true) . Inflector::humanize($this->action) . ' :: ' . $this->scaffoldTitle;
00176 
00177         $modelClass = $this->controller->modelClass;
00178         $primaryKey = $this->ScaffoldModel->primaryKey;
00179         $displayField = $this->ScaffoldModel->displayField;
00180         $singularVar = Inflector::variable($modelClass);
00181         $pluralVar = Inflector::variable($this->controller->name);
00182         $singularHumanName = Inflector::humanize($modelClass);
00183         $pluralHumanName = Inflector::humanize($this->controller->name);
00184         $scaffoldFields = array_keys($this->ScaffoldModel->schema());
00185         $associations = $this->__associations();
00186 
00187         $this->controller->set(compact('modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
00188                                 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'));
00189 
00190         if ($this->controller->view && $this->controller->view !== 'Theme') {
00191             $this->controller->view = 'scaffold';
00192         }
00193         $this->__scaffold($params);
00194     }
00195 /**
00196  * Outputs the content of a scaffold method passing it through the Controller::afterFilter()
00197  *
00198  * @access private
00199  */
00200     function _output() {
00201         $this->controller->afterFilter();
00202         echo($this->controller->output);
00203     }
00204 /**
00205  * Renders a view action of scaffolded model.
00206  *
00207  * @param array $params Parameters for scaffolding
00208  * @return mixed A rendered view of a row from Models database table
00209  * @access private
00210  */
00211     function __scaffoldView($params) {
00212         if ($this->controller->_beforeScaffold('view')) {
00213 
00214             if (isset($params['pass'][0])) {
00215                 $this->ScaffoldModel->id = $params['pass'][0];
00216             } elseif (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00217                 $this->controller->Session->setFlash(sprintf(__("No id set for %s::view()", true), Inflector::humanize($this->modelKey)));
00218                 $this->controller->redirect($this->redirect);
00219             } else {
00220                 return $this->controller->flash(sprintf(__("No id set for %s::view()", true), Inflector::humanize($this->modelKey)),
00221                                                                         '/' . Inflector::underscore($this->controller->viewPath));
00222             }
00223             $this->ScaffoldModel->recursive = 1;
00224             $this->controller->data = $this->ScaffoldModel->read();
00225             $this->controller->set(Inflector::variable($this->controller->modelClass), $this->controller->data);
00226             $this->controller->render($this->action, $this->layout);
00227             $this->_output();
00228         } elseif ($this->controller->_scaffoldError('view') === false) {
00229             return $this->__scaffoldError();
00230         }
00231     }
00232 /**
00233  * Renders index action of scaffolded model.
00234  *
00235  * @param array $params Parameters for scaffolding
00236  * @return mixed A rendered view listing rows from Models database table
00237  * @access private
00238  */
00239     function __scaffoldIndex($params) {
00240         if ($this->controller->_beforeScaffold('index')) {
00241             $this->ScaffoldModel->recursive = 0;
00242             $this->controller->set(Inflector::variable($this->controller->name), $this->controller->paginate());    
00243             $this->controller->render($this->action, $this->layout);
00244             $this->_output();
00245         } elseif ($this->controller->_scaffoldError('index') === false) {
00246             return $this->__scaffoldError();
00247         }
00248     }
00249 /**
00250  * Renders an add or edit action for scaffolded model.
00251  *
00252  * @param string $action Action (add or edit)
00253  * @return mixed A rendered view with a form to edit or add a record in the Models database table
00254  * @access private
00255  */
00256     function __scaffoldForm($action = 'edit') {
00257         $this->controller->render($action, $this->layout);
00258         $this->_output();
00259     }
00260 /**
00261  * Saves or updates the scaffolded model.
00262  *
00263  * @param array $params Parameters for scaffolding
00264  * @param string $action add or edt
00265  * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
00266  * @access private
00267  */
00268     function __scaffoldSave($params = array(), $action = 'edit') {
00269         $formAction = 'edit';
00270         $success = __('updated', true);
00271         if ($action === 'add') {
00272             $formAction = 'add';
00273             $success = __('saved', true);
00274         }
00275 
00276         if ($this->controller->_beforeScaffold($action)) {
00277             if ($action == 'edit') {
00278                 if(isset($params['pass'][0])) {
00279                     $this->ScaffoldModel->id = $params['pass'][0];
00280                 }
00281 
00282                 if(!$this->ScaffoldModel->exists()) {
00283                     if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00284                         $this->controller->Session->setFlash(sprintf(__("Invalid id for %s::edit()", true), Inflector::humanize($this->modelKey)));
00285                         $this->controller->redirect($this->redirect);
00286                     } else {
00287                         return $this->controller->flash(sprintf(__("Invalid id for %s::edit()", true), Inflector::humanize($this->modelKey)), $this->redirect);
00288                     }
00289                 }
00290             }
00291 
00292             if (!empty($this->controller->data)) {
00293                 if ($action == 'create') {
00294                     $this->ScaffoldModel->create();
00295                 }
00296 
00297                 if ($this->ScaffoldModel->save($this->controller->data)) {
00298                     if ($this->controller->_afterScaffoldSave($action)) {
00299                         if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00300                             $this->controller->Session->setFlash(sprintf(__('The %1$s has been %2$s', true), Inflector::humanize($this->modelClass), $success));
00301                             $this->controller->redirect($this->redirect);
00302                         } else {
00303                             return $this->controller->flash(sprintf(__('The %1$s has been %2$s', true), Inflector::humanize($this->modelClass), $success), $this->redirect);
00304                         }
00305                     } else {
00306                         return $this->controller->_afterScaffoldSaveError($action);
00307                     }
00308                 } else {
00309                     if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00310                         $this->controller->Session->setFlash(__('Please correct errors below.', true));
00311                     }
00312                 }
00313             }
00314 
00315             if (empty($this->controller->data)) {
00316                 if ($this->ScaffoldModel->id) {
00317                     $this->controller->data = $this->ScaffoldModel->read();
00318                 } else {
00319                     $this->controller->data = $this->ScaffoldModel->create();
00320                 }
00321             }
00322 
00323             foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
00324                 $varName = Inflector::variable(Inflector::pluralize(preg_replace('/_id$/', '', $assocData['foreignKey'])));
00325                 $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
00326             }
00327             foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
00328                 $varName = Inflector::variable(Inflector::pluralize($assocName));
00329                 $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
00330             }
00331 
00332             return $this->__scaffoldForm($formAction);
00333         } elseif ($this->controller->_scaffoldError($action) === false) {
00334             return $this->__scaffoldError();
00335         }
00336     }
00337 /**
00338  * Performs a delete on given scaffolded Model.
00339  *
00340  * @param array $params Parameters for scaffolding
00341  * @return mixed Success on delete, error if delete fails
00342  * @access private
00343  */
00344     function __scaffoldDelete($params = array()) {
00345         if ($this->controller->_beforeScaffold('delete')) {
00346             if (isset($params['pass'][0])) {
00347                 $id = $params['pass'][0];
00348             } elseif (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00349                 $this->controller->Session->setFlash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)));
00350                 $this->controller->redirect($this->redirect);
00351             } else {
00352                 return $this->controller->flash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)),
00353                                                                     '/' . Inflector::underscore($this->controller->viewPath));
00354             }
00355 
00356             if ($this->ScaffoldModel->del($id)) {
00357                 if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00358                     $this->controller->Session->setFlash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id));
00359                     $this->controller->redirect($this->redirect);
00360                 } else {
00361                     return $this->controller->flash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
00362                 }
00363             } else {
00364                 if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
00365                     $this->controller->Session->setFlash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id));
00366                     $this->controller->redirect($this->redirect);
00367                 } else {
00368                     return $this->controller->flash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
00369                 }
00370             }
00371         } elseif ($this->controller->_scaffoldError('delete') === false) {
00372             return $this->__scaffoldError();
00373         }
00374     }
00375 /**
00376  * Show a scaffold error
00377  *
00378  * @return mixed A rendered view showing the error
00379  * @access private
00380  */
00381     function __scaffoldError() {
00382         return $this->controller->render('error', $this->layout);
00383         $this->_output();
00384     }
00385 /**
00386  * When methods are now present in a controller
00387  * scaffoldView is used to call default Scaffold methods if:
00388  * <code>
00389  * var $scaffold;
00390  * </code>
00391  * is placed in the controller's class definition.
00392  *
00393  * @param array $params Parameters for scaffolding
00394  * @return mixed A rendered view of scaffold action, or showing the error
00395  * @access private
00396  */
00397     function __scaffold($params) {
00398         $db = &ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
00399         $admin = Configure::read('Routing.admin');
00400 
00401         if (isset($db)) {
00402             if (empty($this->scaffoldActions)) {
00403                 $this->scaffoldActions = array('index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete');
00404             } elseif (!empty($admin) && $this->scaffoldActions === $admin) {
00405                 $this->scaffoldActions = array($admin .'_index', $admin .'_list', $admin .'_view', $admin .'_add', $admin .'_create', $admin .'_edit', $admin .'_update', $admin .'_delete');
00406             }
00407 
00408             if (in_array($params['action'], $this->scaffoldActions)) {
00409                 if (!empty($admin)) {
00410                     $params['action'] = str_replace($admin . '_', '', $params['action']);
00411                 }
00412                 switch($params['action']) {
00413                     case 'index':
00414                         $this->__scaffoldIndex($params);
00415                     break;
00416                     case 'view':
00417                         $this->__scaffoldView($params);
00418                     break;
00419                     case 'list':
00420                         $this->__scaffoldIndex($params);
00421                     break;
00422                     case 'add':
00423                         $this->__scaffoldSave($params, 'add');
00424                     break;
00425                     case 'edit':
00426                         $this->__scaffoldSave($params, 'edit');
00427                     break;
00428                     case 'create':
00429                         $this->__scaffoldSave($params, 'add');
00430                     break;
00431                     case 'update':
00432                         $this->__scaffoldSave($params, 'edit');
00433                     break;
00434                     case 'delete':
00435                         $this->__scaffoldDelete($params);
00436                     break;
00437                 }
00438             } else {
00439                 return $this->cakeError('missingAction', array(array('className' => $this->controller->name . "Controller",
00440                                                                                         'base' => $this->controller->base,
00441                                                                                         'action' => $this->action,
00442                                                                                         'webroot' => $this->controller->webroot)));
00443             }
00444         } else {
00445             return $this->cakeError('missingDatabase', array(array('webroot' => $this->controller->webroot)));
00446         }
00447     }
00448 /**
00449  * Returns associations for controllers models.
00450  *
00451  * @return array Associations for model
00452  * @access private
00453  */
00454     function __associations() {
00455         $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
00456         $associations = array();
00457 
00458         foreach ($keys as $key => $type){
00459             foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
00460                 $associations[$type][$assocKey]['primaryKey'] = $this->ScaffoldModel->{$assocKey}->primaryKey;
00461                 $associations[$type][$assocKey]['displayField'] = $this->ScaffoldModel->{$assocKey}->displayField;
00462                 $associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey'];
00463                 $associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($assocData['className']));
00464             }
00465         }
00466         return $associations;
00467     }
00468 }
00469 
00470 /**
00471  * Scaffold View.
00472  *
00473  * @package     cake
00474  * @subpackage  cake.cake.libs.controller
00475 */
00476 if (!class_exists('ThemeView')) {
00477     App::import('View', 'Theme');
00478 }
00479 
00480 class ScaffoldView extends ThemeView {
00481 /**
00482  * Override _getViewFileName
00483  *
00484  * @return string action
00485  * @access protected
00486  */
00487     function _getViewFileName($name = null) {
00488         if ($name === null) {
00489             $name = $this->action;
00490         }
00491         $name = Inflector::underscore($name);
00492         $scaffoldAction = 'scaffold.'.$name;
00493 
00494         if (!is_null($this->subDir)) {
00495             $subDir = strtolower($this->subDir) . DS;
00496         } else {
00497             $subDir = null;
00498         }
00499 
00500         if ($name === 'add') {
00501             $name = 'edit';
00502         }
00503 
00504         $names[] = $this->viewPath . DS . $subDir . $scaffoldAction;
00505         $names[] = 'scaffolds' . DS . $subDir . $name;
00506         
00507         $admin = Configure::read('Routing.admin');
00508         if (!empty($admin) && strpos($name, $admin.'_') !== false) {
00509             $names[] = 'scaffolds' . DS . $subDir . substr($name, strlen($admin) +1);
00510         }
00511         $paths = $this->_paths($this->plugin);
00512 
00513         foreach ($paths as $path) {
00514             foreach ($names as $name) {
00515                 if (file_exists($path . $name . $this->ext)) {
00516                     return $path . $name . $this->ext;
00517                 } elseif (file_exists($path . $name . '.ctp')) {
00518                     return $path . $name . '.thtml';
00519                 } elseif (file_exists($path . $name . '.thtml')) {
00520                     return $path . $name . '.thtml';
00521                 }
00522             }
00523         }
00524 
00525         if ($name === 'scaffolds' . DS . $subDir . 'error') {
00526             return LIBS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
00527         }
00528 
00529         return $this->_missingView($paths[0] . $name . $this->ext, 'missingView');
00530     }
00531 }
00532 ?>