CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • BakeTask
  • ControllerTask
  • DbConfigTask
  • ExtractTask
  • FixtureTask
  • ModelTask
  • PluginTask
  • ProjectTask
  • TemplateTask
  • TestTask
  • ViewTask
  1: <?php
  2: /**
  3:  * The ControllerTask handles creating and updating controller files.
  4:  *
  5:  * PHP 5
  6:  *
  7:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8:  * Copyright 2005-2012, Cake Software Foundation, Inc.
  9:  *
 10:  * Licensed under The MIT License
 11:  * Redistributions of files must retain the above copyright notice.
 12:  *
 13:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 14:  * @link          http://cakephp.org CakePHP(tm) Project
 15:  * @since         CakePHP(tm) v 1.2
 16:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 17:  */
 18: 
 19: App::uses('AppShell', 'Console/Command');
 20: App::uses('BakeTask', 'Console/Command/Task');
 21: App::uses('AppModel', 'Model');
 22: 
 23: /**
 24:  * Task class for creating and updating controller files.
 25:  *
 26:  * @package       Cake.Console.Command.Task
 27:  */
 28: class ControllerTask extends BakeTask {
 29: 
 30: /**
 31:  * Tasks to be loaded by this Task
 32:  *
 33:  * @var array
 34:  */
 35:     public $tasks = array('Model', 'Test', 'Template', 'DbConfig', 'Project');
 36: 
 37: /**
 38:  * path to Controller directory
 39:  *
 40:  * @var array
 41:  */
 42:     public $path = null;
 43: 
 44: /**
 45:  * Override initialize
 46:  *
 47:  * @return void
 48:  */
 49:     public function initialize() {
 50:         $this->path = current(App::path('Controller'));
 51:     }
 52: 
 53: /**
 54:  * Execution method always used for tasks
 55:  *
 56:  * @return void
 57:  */
 58:     public function execute() {
 59:         parent::execute();
 60:         if (empty($this->args)) {
 61:             return $this->_interactive();
 62:         }
 63: 
 64:         if (isset($this->args[0])) {
 65:             if (!isset($this->connection)) {
 66:                 $this->connection = 'default';
 67:             }
 68:             if (strtolower($this->args[0]) == 'all') {
 69:                 return $this->all();
 70:             }
 71: 
 72:             $controller = $this->_controllerName($this->args[0]);
 73:             $actions = '';
 74: 
 75:             if (!empty($this->params['public'])) {
 76:                 $this->out(__d('cake_console', 'Baking basic crud methods for ') . $controller);
 77:                 $actions .= $this->bakeActions($controller);
 78:             }
 79:             if (!empty($this->params['admin'])) {
 80:                 $admin = $this->Project->getPrefix();
 81:                 if ($admin) {
 82:                     $this->out(__d('cake_console', 'Adding %s methods', $admin));
 83:                     $actions .= "\n" . $this->bakeActions($controller, $admin);
 84:                 }
 85:             }
 86:             if (empty($actions)) {
 87:                 $actions = 'scaffold';
 88:             }
 89: 
 90:             if ($this->bake($controller, $actions)) {
 91:                 if ($this->_checkUnitTest()) {
 92:                     $this->bakeTest($controller);
 93:                 }
 94:             }
 95:         }
 96:     }
 97: 
 98: /**
 99:  * Bake All the controllers at once.  Will only bake controllers for models that exist.
100:  *
101:  * @return void
102:  */
103:     public function all() {
104:         $this->interactive = false;
105:         $this->listAll($this->connection, false);
106:         ClassRegistry::config('Model', array('ds' => $this->connection));
107:         $unitTestExists = $this->_checkUnitTest();
108: 
109:         $admin = false;
110:         if (!empty($this->params['admin'])) {
111:             $admin = $this->Project->getPrefix();
112:         }
113: 
114:         foreach ($this->__tables as $table) {
115:             $model = $this->_modelName($table);
116:             $controller = $this->_controllerName($model);
117:             App::uses($model, 'Model');
118:             if (class_exists($model)) {
119:                 $actions = $this->bakeActions($controller);
120:                 if ($admin) {
121:                     $this->out(__d('cake_console', 'Adding %s methods', $admin));
122:                     $actions .= "\n" . $this->bakeActions($controller, $admin);
123:                 }
124:                 if ($this->bake($controller, $actions) && $unitTestExists) {
125:                     $this->bakeTest($controller);
126:                 }
127:             }
128:         }
129:     }
130: 
131: /**
132:  * Interactive
133:  *
134:  * @return void
135:  */
136:     protected function _interactive() {
137:         $this->interactive = true;
138:         $this->hr();
139:         $this->out(__d('cake_console', "Bake Controller\nPath: %s", $this->getPath()));
140:         $this->hr();
141: 
142:         if (empty($this->connection)) {
143:             $this->connection = $this->DbConfig->getConfig();
144:         }
145: 
146:         $controllerName = $this->getName();
147:         $this->hr();
148:         $this->out(__d('cake_console', 'Baking %sController', $controllerName));
149:         $this->hr();
150: 
151:         $helpers = $components = array();
152:         $actions = '';
153:         $wannaUseSession = 'y';
154:         $wannaBakeAdminCrud = 'n';
155:         $useDynamicScaffold = 'n';
156:         $wannaBakeCrud = 'y';
157: 
158:         $question[] = __d('cake_console', "Would you like to build your controller interactively?");
159:         if (file_exists($this->path . $controllerName . 'Controller.php')) {
160:             $question[] = __d('cake_console', "Warning: Choosing no will overwrite the %sController.", $controllerName);
161:         }
162:         $doItInteractive = $this->in(implode("\n", $question), array('y', 'n'), 'y');
163: 
164:         if (strtolower($doItInteractive) == 'y') {
165:             $this->interactive = true;
166:             $useDynamicScaffold = $this->in(
167:                 __d('cake_console', "Would you like to use dynamic scaffolding?"), array('y', 'n'), 'n'
168:             );
169: 
170:             if (strtolower($useDynamicScaffold) == 'y') {
171:                 $wannaBakeCrud = 'n';
172:                 $actions = 'scaffold';
173:             } else {
174:                 list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
175: 
176:                 $helpers = $this->doHelpers();
177:                 $components = $this->doComponents();
178: 
179:                 $wannaUseSession = $this->in(
180:                     __d('cake_console', "Would you like to use Session flash messages?"), array('y','n'), 'y'
181:                 );
182:             }
183:         } else {
184:             list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
185:         }
186: 
187:         if (strtolower($wannaBakeCrud) == 'y') {
188:             $actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) == 'y');
189:         }
190:         if (strtolower($wannaBakeAdminCrud) == 'y') {
191:             $admin = $this->Project->getPrefix();
192:             $actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) == 'y');
193:         }
194: 
195:         $baked = false;
196:         if ($this->interactive === true) {
197:             $this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
198:             $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y','n'), 'y');
199: 
200:             if (strtolower($looksGood) == 'y') {
201:                 $baked = $this->bake($controllerName, $actions, $helpers, $components);
202:                 if ($baked && $this->_checkUnitTest()) {
203:                     $this->bakeTest($controllerName);
204:                 }
205:             }
206:         } else {
207:             $baked = $this->bake($controllerName, $actions, $helpers, $components);
208:             if ($baked && $this->_checkUnitTest()) {
209:                 $this->bakeTest($controllerName);
210:             }
211:         }
212:         return $baked;
213:     }
214: 
215: /**
216:  * Confirm a to be baked controller with the user
217:  *
218:  * @param string $controllerName
219:  * @param string $useDynamicScaffold
220:  * @param array $helpers
221:  * @param array $components
222:  * @return void
223:  */
224:     public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
225:         $this->out();
226:         $this->hr();
227:         $this->out(__d('cake_console', 'The following controller will be created:'));
228:         $this->hr();
229:         $this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
230: 
231:         if (strtolower($useDynamicScaffold) == 'y') {
232:             $this->out("public \$scaffold;");
233:         }
234: 
235:         $properties = array(
236:             'helpers' => __d('cake_console', 'Helpers:'),
237:             'components' => __d('cake_console', 'Components:'),
238:         );
239: 
240:         foreach ($properties as $var => $title) {
241:             if (count($$var)) {
242:                 $output = '';
243:                 $length = count($$var);
244:                 foreach ($$var as $i => $propElement) {
245:                     if ($i != $length - 1) {
246:                         $output .= ucfirst($propElement) . ', ';
247:                     } else {
248:                         $output .= ucfirst($propElement);
249:                     }
250:                 }
251:                 $this->out($title . "\n\t" . $output);
252:             }
253:         }
254:         $this->hr();
255:     }
256: 
257: /**
258:  * Interact with the user and ask about which methods (admin or regular they want to bake)
259:  *
260:  * @return array Array containing (bakeRegular, bakeAdmin) answers
261:  */
262:     protected function _askAboutMethods() {
263:         $wannaBakeCrud = $this->in(
264:             __d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
265:             array('y','n'), 'n'
266:         );
267:         $wannaBakeAdminCrud = $this->in(
268:             __d('cake_console', "Would you like to create the basic class methods for admin routing?"),
269:             array('y','n'), 'n'
270:         );
271:         return array($wannaBakeCrud, $wannaBakeAdminCrud);
272:     }
273: 
274: /**
275:  * Bake scaffold actions
276:  *
277:  * @param string $controllerName Controller name
278:  * @param string $admin Admin route to use
279:  * @param boolean $wannaUseSession Set to true to use sessions, false otherwise
280:  * @return string Baked actions
281:  */
282:     public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
283:         $currentModelName = $modelImport = $this->_modelName($controllerName);
284:         $plugin = $this->plugin;
285:         if ($plugin) {
286:             $plugin .= '.';
287:         }
288:         App::uses($modelImport, $plugin . 'Model');
289:         if (!class_exists($modelImport)) {
290:             $this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
291:             $this->_stop();
292:         }
293: 
294:         $modelObj = ClassRegistry::init($currentModelName);
295:         $controllerPath = $this->_controllerPath($controllerName);
296:         $pluralName = $this->_pluralName($currentModelName);
297:         $singularName = Inflector::variable($currentModelName);
298:         $singularHumanName = $this->_singularHumanName($controllerName);
299:         $pluralHumanName = $this->_pluralName($controllerName);
300:         $displayField = $modelObj->displayField;
301:         $primaryKey = $modelObj->primaryKey;
302: 
303:         $this->Template->set(compact(
304:             'plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
305:             'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
306:             'displayField', 'primaryKey'
307:         ));
308:         $actions = $this->Template->generate('actions', 'controller_actions');
309:         return $actions;
310:     }
311: 
312: /**
313:  * Assembles and writes a Controller file
314:  *
315:  * @param string $controllerName Controller name already pluralized and correctly cased.
316:  * @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
317:  * @param array $helpers Helpers to use in controller
318:  * @param array $components Components to use in controller
319:  * @return string Baked controller
320:  */
321:     public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
322:         $this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
323: 
324:         $isScaffold = ($actions === 'scaffold') ? true : false;
325: 
326:         $this->Template->set(array(
327:             'plugin' => $this->plugin,
328:             'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
329:         ));
330:         $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
331:         $contents = $this->Template->generate('classes', 'controller');
332: 
333:         $path = $this->getPath();
334:         $filename = $path . $controllerName . 'Controller.php';
335:         if ($this->createFile($filename, $contents)) {
336:             return $contents;
337:         }
338:         return false;
339:     }
340: 
341: /**
342:  * Assembles and writes a unit test file
343:  *
344:  * @param string $className Controller class name
345:  * @return string Baked test
346:  */
347:     public function bakeTest($className) {
348:         $this->Test->plugin = $this->plugin;
349:         $this->Test->connection = $this->connection;
350:         $this->Test->interactive = $this->interactive;
351:         return $this->Test->bake('Controller', $className);
352:     }
353: 
354: /**
355:  * Interact with the user and get a list of additional helpers
356:  *
357:  * @return array Helpers that the user wants to use.
358:  */
359:     public function doHelpers() {
360:         return $this->_doPropertyChoices(
361:             __d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
362:             __d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'")
363:         );
364:     }
365: 
366: /**
367:  * Interact with the user and get a list of additional components
368:  *
369:  * @return array Components the user wants to use.
370:  */
371:     public function doComponents() {
372:         return $this->_doPropertyChoices(
373:             __d('cake_console', "Would you like this controller to use any components?"),
374:             __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
375:         );
376:     }
377: 
378: /**
379:  * Common code for property choice handling.
380:  *
381:  * @param string $prompt A yes/no question to precede the list
382:  * @param string $example A question for a comma separated list, with examples.
383:  * @return array Array of values for property.
384:  */
385:     protected function _doPropertyChoices($prompt, $example) {
386:         $proceed = $this->in($prompt, array('y','n'), 'n');
387:         $property = array();
388:         if (strtolower($proceed) == 'y') {
389:             $propertyList = $this->in($example);
390:             $propertyListTrimmed = str_replace(' ', '', $propertyList);
391:             $property = explode(',', $propertyListTrimmed);
392:         }
393:         return array_filter($property);
394:     }
395: 
396: /**
397:  * Outputs and gets the list of possible controllers from database
398:  *
399:  * @param string $useDbConfig Database configuration name
400:  * @return array Set of controllers
401:  */
402:     public function listAll($useDbConfig = null) {
403:         if (is_null($useDbConfig)) {
404:             $useDbConfig = $this->connection;
405:         }
406:         $this->__tables = $this->Model->getAllTables($useDbConfig);
407: 
408:         if ($this->interactive == true) {
409:             $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
410:             $this->hr();
411:             $this->_controllerNames = array();
412:             $count = count($this->__tables);
413:             for ($i = 0; $i < $count; $i++) {
414:                 $this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
415:                 $this->out(sprintf("%2d. %s", $i + 1, $this->_controllerNames[$i]));
416:             }
417:             return $this->_controllerNames;
418:         }
419:         return $this->__tables;
420:     }
421: 
422: /**
423:  * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
424:  *
425:  * @param string $useDbConfig Connection name to get a controller name for.
426:  * @return string Controller name
427:  */
428:     public function getName($useDbConfig = null) {
429:         $controllers = $this->listAll($useDbConfig);
430:         $enteredController = '';
431: 
432:         while ($enteredController == '') {
433:             $enteredController = $this->in(__d('cake_console', "Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit"), null, 'q');
434:             if ($enteredController === 'q') {
435:                 $this->out(__d('cake_console', 'Exit'));
436:                 return $this->_stop();
437:             }
438: 
439:             if ($enteredController == '' || intval($enteredController) > count($controllers)) {
440:                 $this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
441:                 $enteredController = '';
442:             }
443:         }
444: 
445:         if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers) ) {
446:             $controllerName = $controllers[intval($enteredController) - 1];
447:         } else {
448:             $controllerName = Inflector::camelize($enteredController);
449:         }
450:         return $controllerName;
451:     }
452: 
453: /**
454:  * get the option parser.
455:  *
456:  * @return void
457:  */
458:     public function getOptionParser() {
459:         $parser = parent::getOptionParser();
460:         return $parser->description(
461:                 __d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.')
462:             )->addArgument('name', array(
463:                 'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
464:             ))->addOption('public', array(
465:                 'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
466:                 'boolean' => true
467:             ))->addOption('admin', array(
468:                 'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
469:                 'boolean' => true
470:             ))->addOption('plugin', array(
471:                 'short' => 'p',
472:                 'help' => __d('cake_console', 'Plugin to bake the controller into.')
473:             ))->addOption('connection', array(
474:                 'short' => 'c',
475:                 'help' => __d('cake_console', 'The connection the controller\'s model is on.')
476:             ))->addSubcommand('all', array(
477:                 'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
478:             ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
479:     }
480: 
481: }
482: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs