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.4 API

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