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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 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
  • None

Classes

  • BakeTask
  • CommandTask
  • 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 (https://cakephp.org)
  6:  * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
 13:  * @link          https://cakephp.org CakePHP(tm) Project
 14:  * @since         CakePHP(tm) v 1.2
 15:  * @license       https://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 the FlashComponent to display flash messages?"), array('y', 'n'), 'y'
186:                 );
187: 
188:                 if (strtolower($wannaUseSession) === 'y') {
189:                     array_push($components, 'Session', 'Flash');
190:                 }
191:                 array_unique($components);
192:             }
193:         } else {
194:             list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
195:         }
196: 
197:         if (strtolower($wannaBakeCrud) === 'y') {
198:             $actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) === 'y');
199:         }
200:         if (strtolower($wannaBakeAdminCrud) === 'y') {
201:             $admin = $this->Project->getPrefix();
202:             $actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) === 'y');
203:         }
204: 
205:         $baked = false;
206:         if ($this->interactive === true) {
207:             $this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
208:             $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
209: 
210:             if (strtolower($looksGood) === 'y') {
211:                 $baked = $this->bake($controllerName, $actions, $helpers, $components);
212:                 if ($baked && $this->_checkUnitTest()) {
213:                     $this->bakeTest($controllerName);
214:                 }
215:             }
216:         } else {
217:             $baked = $this->bake($controllerName, $actions, $helpers, $components);
218:             if ($baked && $this->_checkUnitTest()) {
219:                 $this->bakeTest($controllerName);
220:             }
221:         }
222:         return $baked;
223:     }
224: 
225: /**
226:  * Confirm a to be baked controller with the user
227:  *
228:  * @param string $controllerName The name of the controller.
229:  * @param string $useDynamicScaffold Whether or not to use dynamic scaffolds.
230:  * @param array $helpers The list of helpers to include.
231:  * @param array $components The list of components to include.
232:  * @return void
233:  */
234:     public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
235:         $this->out();
236:         $this->hr();
237:         $this->out(__d('cake_console', 'The following controller will be created:'));
238:         $this->hr();
239:         $this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
240: 
241:         if (strtolower($useDynamicScaffold) === 'y') {
242:             $this->out("public \$scaffold;");
243:         }
244: 
245:         $properties = array(
246:             'helpers' => __d('cake_console', 'Helpers:'),
247:             'components' => __d('cake_console', 'Components:'),
248:         );
249: 
250:         foreach ($properties as $var => $title) {
251:             if (count(${$var})) {
252:                 $output = '';
253:                 $length = count(${$var});
254:                 foreach (${$var} as $i => $propElement) {
255:                     if ($i != $length - 1) {
256:                         $output .= ucfirst($propElement) . ', ';
257:                     } else {
258:                         $output .= ucfirst($propElement);
259:                     }
260:                 }
261:                 $this->out($title . "\n\t" . $output);
262:             }
263:         }
264:         $this->hr();
265:     }
266: 
267: /**
268:  * Interact with the user and ask about which methods (admin or regular they want to bake)
269:  *
270:  * @return array Array containing (bakeRegular, bakeAdmin) answers
271:  */
272:     protected function _askAboutMethods() {
273:         $wannaBakeCrud = $this->in(
274:             __d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
275:             array('y', 'n'), 'n'
276:         );
277:         $wannaBakeAdminCrud = $this->in(
278:             __d('cake_console', "Would you like to create the basic class methods for admin routing?"),
279:             array('y', 'n'), 'n'
280:         );
281:         return array($wannaBakeCrud, $wannaBakeAdminCrud);
282:     }
283: 
284: /**
285:  * Bake scaffold actions
286:  *
287:  * @param string $controllerName Controller name
288:  * @param string $admin Admin route to use
289:  * @param bool $wannaUseSession Set to true to use sessions, false otherwise
290:  * @return string Baked actions
291:  */
292:     public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
293:         $currentModelName = $modelImport = $this->_modelName($controllerName);
294:         $plugin = $this->plugin;
295:         if ($plugin) {
296:             $plugin .= '.';
297:         }
298:         App::uses($modelImport, $plugin . 'Model');
299:         if (!class_exists($modelImport)) {
300:             $this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
301:             return $this->_stop();
302:         }
303: 
304:         $modelObj = ClassRegistry::init($currentModelName);
305:         $controllerPath = $this->_controllerPath($controllerName);
306:         $pluralName = $this->_pluralName($currentModelName);
307:         $singularName = Inflector::variable($currentModelName);
308:         $singularHumanName = $this->_singularHumanName($controllerName);
309:         $pluralHumanName = $this->_pluralName($controllerName);
310:         $displayField = $modelObj->displayField;
311:         $primaryKey = $modelObj->primaryKey;
312: 
313:         $this->Template->set(compact(
314:             'plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
315:             'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
316:             'displayField', 'primaryKey'
317:         ));
318:         $actions = $this->Template->generate('actions', 'controller_actions');
319:         return $actions;
320:     }
321: 
322: /**
323:  * Assembles and writes a Controller file
324:  *
325:  * @param string $controllerName Controller name already pluralized and correctly cased.
326:  * @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
327:  * @param array $helpers Helpers to use in controller
328:  * @param array $components Components to use in controller
329:  * @return string Baked controller
330:  */
331:     public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
332:         $this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
333: 
334:         if ($helpers === null) {
335:             $helpers = array();
336:         }
337:         if ($components === null) {
338:             $components = array();
339:         }
340:         $isScaffold = ($actions === 'scaffold') ? true : false;
341: 
342:         $this->Template->set(array(
343:             'plugin' => $this->plugin,
344:             'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
345:         ));
346: 
347:         if (!in_array('Paginator', (array)$components)) {
348:             $components[] = 'Paginator';
349:         }
350: 
351:         $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
352:         $contents = $this->Template->generate('classes', 'controller');
353: 
354:         $path = $this->getPath();
355:         $filename = $path . $controllerName . 'Controller.php';
356:         if ($this->createFile($filename, $contents)) {
357:             return $contents;
358:         }
359:         return false;
360:     }
361: 
362: /**
363:  * Assembles and writes a unit test file
364:  *
365:  * @param string $className Controller class name
366:  * @return string Baked test
367:  */
368:     public function bakeTest($className) {
369:         $this->Test->plugin = $this->plugin;
370:         $this->Test->connection = $this->connection;
371:         $this->Test->interactive = $this->interactive;
372:         return $this->Test->bake('Controller', $className);
373:     }
374: 
375: /**
376:  * Interact with the user and get a list of additional helpers
377:  *
378:  * @return array Helpers that the user wants to use.
379:  */
380:     public function doHelpers() {
381:         return $this->_doPropertyChoices(
382:             __d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
383:             __d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Text, Js, Time'")
384:         );
385:     }
386: 
387: /**
388:  * Interact with the user and get a list of additional components
389:  *
390:  * @return array Components the user wants to use.
391:  */
392:     public function doComponents() {
393:         $components = array('Paginator');
394:         return array_merge($components, $this->_doPropertyChoices(
395:             __d('cake_console', "Would you like this controller to use other components\nbesides PaginatorComponent?"),
396:             __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
397:         ));
398:     }
399: 
400: /**
401:  * Common code for property choice handling.
402:  *
403:  * @param string $prompt A yes/no question to precede the list
404:  * @param string $example A question for a comma separated list, with examples.
405:  * @return array Array of values for property.
406:  */
407:     protected function _doPropertyChoices($prompt, $example) {
408:         $proceed = $this->in($prompt, array('y', 'n'), 'n');
409:         $property = array();
410:         if (strtolower($proceed) === 'y') {
411:             $propertyList = $this->in($example);
412:             $propertyListTrimmed = str_replace(' ', '', $propertyList);
413:             $property = explode(',', $propertyListTrimmed);
414:         }
415:         return array_filter($property);
416:     }
417: 
418: /**
419:  * Outputs and gets the list of possible controllers from database
420:  *
421:  * @param string $useDbConfig Database configuration name
422:  * @return array Set of controllers
423:  */
424:     public function listAll($useDbConfig = null) {
425:         if ($useDbConfig === null) {
426:             $useDbConfig = $this->connection;
427:         }
428:         $this->__tables = $this->Model->getAllTables($useDbConfig);
429: 
430:         if ($this->interactive) {
431:             $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
432:             $this->hr();
433:             $this->_controllerNames = array();
434:             $count = count($this->__tables);
435:             for ($i = 0; $i < $count; $i++) {
436:                 $this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
437:                 $this->out(sprintf("%2d. %s", $i + 1, $this->_controllerNames[$i]));
438:             }
439:             return $this->_controllerNames;
440:         }
441:         return $this->__tables;
442:     }
443: 
444: /**
445:  * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
446:  *
447:  * @param string $useDbConfig Connection name to get a controller name for.
448:  * @return string Controller name
449:  */
450:     public function getName($useDbConfig = null) {
451:         $controllers = $this->listAll($useDbConfig);
452:         $enteredController = '';
453: 
454:         while (!$enteredController) {
455:             $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');
456:             if ($enteredController === 'q') {
457:                 $this->out(__d('cake_console', 'Exit'));
458:                 return $this->_stop();
459:             }
460: 
461:             if (!$enteredController || (int)$enteredController > count($controllers)) {
462:                 $this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
463:                 $enteredController = '';
464:             }
465:         }
466: 
467:         if ((int)$enteredController > 0 && (int)$enteredController <= count($controllers)) {
468:             $controllerName = $controllers[(int)$enteredController - 1];
469:         } else {
470:             $controllerName = Inflector::camelize($enteredController);
471:         }
472:         return $controllerName;
473:     }
474: 
475: /**
476:  * Gets the option parser instance and configures it.
477:  *
478:  * @return ConsoleOptionParser
479:  */
480:     public function getOptionParser() {
481:         $parser = parent::getOptionParser();
482: 
483:         $parser->description(
484:             __d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.'
485:         ))->addArgument('name', array(
486:             'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
487:         ))->addOption('public', array(
488:             'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
489:             'boolean' => true
490:         ))->addOption('admin', array(
491:             'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
492:             'boolean' => true
493:         ))->addOption('plugin', array(
494:             'short' => 'p',
495:             'help' => __d('cake_console', 'Plugin to bake the controller into.')
496:         ))->addOption('connection', array(
497:             'short' => 'c',
498:             'help' => __d('cake_console', 'The connection the controller\'s model is on.')
499:         ))->addOption('theme', array(
500:             'short' => 't',
501:             'help' => __d('cake_console', 'Theme to use when baking code.')
502:         ))->addOption('force', array(
503:             'short' => 'f',
504:             'help' => __d('cake_console', 'Force overwriting existing files without prompting.')
505:         ))->addSubcommand('all', array(
506:             'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
507:         ))->epilog(
508:             __d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.')
509:         );
510: 
511:         return $parser;
512:     }
513: 
514: }
515: 
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