Class ModelTask

Task class for creating and updating model files.

Object
Extended by Shell
Extended by AppShell
Extended by BakeTask
Extended by ModelTask
Package: Cake\Console\Command\Task
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Console/Command/Task/ModelTask.php

Inherited Constants

Properties summary

  • $_modelNames protected
    array
    Holds the model names
  • $_tables protected
    array
    Holds tables found on connection.
  • $_validations protected
    array
    Holds validation method map.
  • $path public
    string
    path to Model directory
  • $skipTables public
    array
    Tables to skip when running all()
  • $tasks public
    array
    tasks

Inherited Properties

Method Summary

  • Finds all possible keys to use on custom associations.
  • _getModelObject() protected
    Get a model object for a class name.
  • _interactive() protected
    Handles interactive baking
  • Print out all the associations of a particular type
  • all() public
    Bake all models at once.
  • bake() public
    Assembles and writes a Model file.
  • bakeFixture() public
    Interact with FixtureTask to automatically bake fixtures when baking models.
  • bakeTest() public
    Assembles and writes a unit test file
  • Interact with the user and confirm associations.
  • doActsAs() public
    Handles behaviors
  • Handles associations
  • Interact with the user and generate additional non-conventional associations
  • Handles Generation and user interaction for creating validation.
  • execute() public
    Execution method always used for tasks
  • Does individual field validation handling.
  • Find belongsTo relations and add them to the associations list.
  • interact with the user to find the displayField value for a model.
  • Find the hasAndBelongsToMany relations and add them to associations list
  • Find the hasOne and hasMany relations and add them to associations list
  • Finds a primary Key in a list of fields.
  • Get an Array of all the tables in the supplied connection will halt the script if no tables are found.

  • getName() public
    Forces the user to specify the model he wants to bake, and returns the selected model name.
  • Gets the option parser instance and configures it.
  • getTable() public
    Interact with the user to determine the table name of a particular model
  • inOptions() public
    Generate a key value list of options and a prompt.
  • Populate the _validations array
  • initialize() public
    Override initialize
  • listAll() public
    outputs the a list of possible models or controllers from database

Method Detail

_generatePossibleKeys()source protected

_generatePossibleKeys( )

Finds all possible keys to use on custom associations.

Returns

array
Array of tables and possible keys

_getModelObject()source protected

_getModelObject( string $className , string $table null )

Get a model object for a class name.

Parameters

string $className
Name of class you want model to be.
string $table optional null
Table name

Returns

Model
Model instance

_interactive()source protected

_interactive( )

Handles interactive baking

Returns

boolean

_printAssociation()source protected

_printAssociation( string $modelName , string $type , string $associations )

Print out all the associations of a particular type

Parameters

string $modelName
Name of the model relations belong to.
string $type
Name of association you want to see. i.e. 'belongsTo'
string $associations
Collection of associations.

all()source public

all( )

Bake all models at once.

bake()source public

bake( string|object $name , array|boolean $data array() )

Assembles and writes a Model file.

Parameters

string|object $name
Model name or object
array|boolean $data optional array()
if array and $name is not an object assume bake data, otherwise boolean.

Returns

string

bakeFixture()source public

bakeFixture( string $className , string $useTable null )

Interact with FixtureTask to automatically bake fixtures when baking models.

Parameters

string $className
Name of class to bake fixture for
string $useTable optional null
Optional table name for fixture to use.

See

FixtureTask::bake

bakeTest()source public

bakeTest( string $className )

Assembles and writes a unit test file

Parameters

string $className
Model class name

Returns

string

confirmAssociations()source public

confirmAssociations( Model $model , array $associations )

Interact with the user and confirm associations.

Parameters

Model $model
Temporary Model instance.
array $associations
Array of associations to be confirmed.

Returns

array
Array of confirmed associations

doActsAs()source public

doActsAs( Model $model )

Handles behaviors

Parameters

Model $model
The model object.

Returns

array
Behaviors

doAssociations()source public

doAssociations( Model $model )

Handles associations

Parameters

Model $model
The model object

Returns

array
Associations

doMoreAssociations()source public

doMoreAssociations( Model $model , array $associations )

Interact with the user and generate additional non-conventional associations

Parameters

Model $model
Temporary model instance
array $associations
Array of associations.

Returns

array
Array of associations.

doValidation()source public

doValidation( Model $model )

Handles Generation and user interaction for creating validation.

Parameters

Model $model
Model to have validations generated for.

Returns

array
validate Array of user selected validations.

execute()source public

execute( )

Execution method always used for tasks

Overrides

BakeTask::execute()

fieldValidation()source public

fieldValidation( string $fieldName , array $metaData , string $primaryKey 'id' )

Does individual field validation handling.

Parameters

string $fieldName
Name of field to be validated.
array $metaData
metadata for field
string $primaryKey optional 'id'
The primary key field.

Returns

array
Array of validation for the field.

findBelongsTo()source public

findBelongsTo( Model $model , array $associations )

Find belongsTo relations and add them to the associations list.

Parameters

Model $model
Model instance of model being generated.
array $associations
Array of in progress associations

Returns

array
Associations with belongsTo added in.

findDisplayField()source public

findDisplayField( array $fields )

interact with the user to find the displayField value for a model.

Parameters

array $fields
Array of fields to look for and choose as a displayField

Returns

mixed
Name of field to use for displayField or false if the user declines to choose

findHasAndBelongsToMany()source public

findHasAndBelongsToMany( Model $model , array $associations )

Find the hasAndBelongsToMany relations and add them to associations list

Parameters

Model $model
Model instance being generated
array $associations
Array of in-progress associations

Returns

array
Associations with hasAndBelongsToMany added in.

findHasOneAndMany()source public

findHasOneAndMany( Model $model , array $associations )

Find the hasOne and hasMany relations and add them to associations list

Parameters

Model $model
Model instance being generated
array $associations
Array of in progress associations

Returns

array
Associations with hasOne and hasMany added in.

findPrimaryKey()source public

findPrimaryKey( array $fields )

Finds a primary Key in a list of fields.

Parameters

array $fields
Array of fields that might have a primary key.

Returns

string
Name of field that is a primary key.

getAllTables()source public

getAllTables( string $useDbConfig null )

Get an Array of all the tables in the supplied connection will halt the script if no tables are found.

Parameters

string $useDbConfig optional null
Connection name to scan.

Returns

array
Array of tables in the database.

getName()source public

getName( string $useDbConfig null )

Forces the user to specify the model he wants to bake, and returns the selected model name.

Parameters

string $useDbConfig optional null
Database config name

Returns

string
The model name

getOptionParser()source public

getOptionParser( )

Gets the option parser instance and configures it.

Returns

ConsoleOptionParser

Overrides

Shell::getOptionParser()

getTable()source public

getTable( string $modelName , string $useDbConfig null )

Interact with the user to determine the table name of a particular model

Parameters

string $modelName
Name of the model you want a table for.
string $useDbConfig optional null
Name of the database config you want to get tables from.

Returns

string
Table name

inOptions()source public

inOptions( array $options , string $prompt null , integer $default null )

Generate a key value list of options and a prompt.

Parameters

array $options
Array of options to use for the selections. indexes must start at 0
string $prompt optional null
Prompt to use for options list.
integer $default optional null
The default option for the given prompt.

Returns

integer
Result of user choice.

initValidations()source public

initValidations( )

Populate the _validations array

initialize()source public

initialize( )

Override initialize

Overrides

Shell::initialize()

listAll()source public

listAll( string $useDbConfig null )

outputs the a list of possible models or controllers from database

Parameters

string $useDbConfig optional null
Database configuration name

Returns

array

Methods inherited from BakeTask

getPath()source public

getPath( )

Gets the path for output. Checks the plugin property and returns the correct path.

Returns

string
Path to output.

startup()source public

startup( )

Disable caching and enable debug for baking. This forces the most current database schema to be used.

Overrides

Shell::startup()

Methods inherited from Shell

__construct()source public

__construct( ConsoleOutput $stdout null , ConsoleOutput $stderr null , ConsoleInput $stdin null )

Constructs this Shell instance.

Parameters

ConsoleOutput $stdout optional null
A ConsoleOutput object for stdout.
ConsoleOutput $stderr optional null
A ConsoleOutput object for stderr.
ConsoleInput $stdin optional null
A ConsoleInput object for stdin.

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell

Overrides

Object::__construct()

__get()source public

__get( string $name )

Overload get for lazy building of tasks

Parameters

string $name
The property name to access.

Returns

Shell
Object of Task

__isset()source public

__isset( string $name )

Lazy loads models using the loadModel() method if declared in $uses

Parameters

string $name
The name of the model to look for.

_checkUnitTest()source protected

_checkUnitTest( )

Action to create a Unit Test

Returns

boolean
Success

_controllerName()source protected

_controllerName( string $name )

Creates the proper controller plural name for the specified controller class name

Parameters

string $name
Controller class name

Returns

string
Controller plural name

_controllerPath()source protected

_controllerPath( string $name )

Creates the proper controller path for the specified controller class name

Parameters

string $name
Controller class name

Returns

string
Path to controller

_displayHelp()source protected

_displayHelp( string $command )

Display the help in the correct format

Parameters

string $command
The command to get help for.

_getInput()source protected

_getInput( string $prompt , string|array $options , string $default )

Prompts the user for input, and returns it.

Parameters

string $prompt
Prompt text.
string|array $options
Array or string of options.
string $default
Default input value.

Returns

Either
the default value, or the user-provided input.

_loadModels()source protected

_loadModels( )

If $uses is an array load each of the models in the array

Returns

boolean

_modelKey()source protected

_modelKey( string $name )

Creates the proper underscored model key for associations

Parameters

string $name
Model class name

Returns

string
Singular model key

_modelName()source protected

_modelName( string $name )

Creates the proper model camelized name (singularized) for the specified name

Parameters

string $name
Name

Returns

string
Camelized and singularized model name

_modelNameFromKey()source protected

_modelNameFromKey( string $key )

Creates the proper model name from a foreign key

Parameters

string $key
Foreign key

Returns

string
Model name

_pluginPath()source protected

_pluginPath( string $pluginName )

Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.

Parameters

string $pluginName
Name of the plugin you want ie. DebugKit

Returns

string
path path to the correct plugin.

_pluralHumanName()source protected

_pluralHumanName( string $name )

Creates the plural human name used in views

Parameters

string $name
Controller name

Returns

string
Plural human name

_pluralName()source protected

_pluralName( string $name )

Creates the plural name for views

Parameters

string $name
Name to use

Returns

string
Plural name for views

_singularHumanName()source protected

_singularHumanName( string $name )

Creates the singular human name used in views

Parameters

string $name
Controller name

Returns

string
Singular human name

_singularName()source protected

_singularName( string $name )

creates the singular name for use in views.

Parameters

string $name
The plural underscored value.

Returns

string
name

_useLogger()source protected

_useLogger( boolean $enable true )

Used to enable or disable logging stream output to stdout and stderr If you don't wish to see in your stdout or stderr everything that is logged through CakeLog, call this function with first param as false

Parameters

boolean $enable optional true
whether to enable CakeLog output or not

_welcome()source protected

_welcome( )

Displays a header for the shell

clear()source public

clear( )

Clear the console

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clear

createFile()source public

createFile( string $path , string $contents )

Creates a file at given path

Parameters

string $path
Where to put the file.
string $contents
Content to put in the file.

Returns

boolean
Success

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile

dispatchShell()source public

dispatchShell( )

Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.

Usage:

With a string command:

return $this->dispatchShell('schema create DbAcl');

Avoid using this form if you have string arguments, with spaces in them. The dispatched will be invoked incorrectly. Only use this form for simple command dispatching.

With an array command:

return $this->dispatchShell('schema', 'create', 'i18n', '--dry');

Returns

mixed
The return of the other shell.

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::dispatchShell

err()source public

err( string|array $message null , integer $newlines 1 )

Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.

Parameters

string|array $message optional null
A string or an array of strings to output
integer $newlines optional 1
Number of newlines to append

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::err

error()source public

error( string $title , string $message null )

Displays a formatted error message and exits the application with status code 1

Parameters

string $title
Title of the error
string $message optional null
An optional error message

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::error

hasMethod()source public

hasMethod( string $name )

Check to see if this shell has a callable method by the given name.

Parameters

string $name
The method name to check.

Returns

boolean

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasMethod

hasTask()source public

hasTask( string $task )

Check to see if this shell has a task with the provided name.

Parameters

string $task
The task name to check.

Returns

boolean
Success

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasTask

helper()source public

helper( string $name )

Load given shell helper class

Parameters

string $name
Name of the helper class. Supports plugin syntax.

Returns

BaseShellHelper
Instance of helper class

Throws

RuntimeException
If invalid class name is provided

hr()source public

hr( integer $newlines 0 , integer $width 63 )

Outputs a series of minus characters to the standard output, acts as a visual separator.

Parameters

integer $newlines optional 0
Number of newlines to pre- and append
integer $width optional 63
Width of the line, defaults to 63

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hr

in()source public

in( string $prompt , string|array $options null , string $default null )

Prompts the user for input, and returns it.

Parameters

string $prompt
Prompt text.
string|array $options optional null
Array or string of options.
string $default optional null
Default input value.

Returns

mixed
Either the default value, or the user-provided input.

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::in

loadModel()source public

loadModel( string $modelClass null , mixed $id null )

Loads and instantiates models required by this shell.

Parameters

string $modelClass optional null
Name of model class to load
mixed $id optional null
Initial ID the instanced model class should have

Returns

mixed
true when single model found and instance created, error returned if model not found.

Throws

MissingModelException
if the model class cannot be found.

loadTasks()source public

loadTasks( )

Loads tasks defined in public $tasks

Returns

boolean

nl()source public

nl( integer $multiplier 1 )

Returns a single or multiple linefeeds sequences.

Parameters

integer $multiplier optional 1
Number of times the linefeed sequence should be repeated

Returns

string

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nl

out()source public

out( string|array $message null , integer $newlines 1 , integer $level Shell::NORMAL )

Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.

Output levels

There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE. The verbose and quiet output levels, map to the verbose and quiet output switches present in most shells. Using Shell::QUIET for a message means it will always display. While using Shell::VERBOSE means it will only display when verbose output is toggled.

Parameters

string|array $message optional null
A string or an array of strings to output
integer $newlines optional 1
Number of newlines to append
integer $level optional Shell::NORMAL
The message's output level, see above.

Returns

integer|boolean
Returns the number of bytes returned from writing to stdout.

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::out

overwrite()source public

overwrite( array|string $message , integer $newlines 1 , integer $size null )

Overwrite some already output text.

Useful for building progress bars, or when you want to replace text already output to the screen with new text.

Warning You cannot overwrite text that contains newlines.

Parameters

array|string $message
The message to output.
integer $newlines optional 1
Number of newlines to append.
integer $size optional null
The number of bytes to overwrite. Defaults to the length of the last message output.

Returns

integer|boolean
Returns the number of bytes returned from writing to stdout.

param()source public

param( string $name )

Safely access the values in $this->params.

Parameters

string $name
The name of the parameter to get.

Returns

string|boolean|null
Value. Will return null if it doesn't exist.

runCommand()source public

runCommand( string $command , array $argv )

Runs the Shell with the provided argv.

Delegates calls to Tasks and resolves methods inside the class. Commands are looked up with the following order:

  • Method on the shell.
  • Matching task name.
  • main() method.

If a shell implements a main() method, all missing method calls will be sent to main() with the original method name in the argv.

Parameters

string $command

The command name to run on this shell. If this argument is empty, and the shell has a main() method, that will be called instead.

array $argv
Array of arguments to run the shell with. This array should be missing the shell name.

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::runCommand

shortPath()source public

shortPath( string $file )

Makes absolute file path easier to read

Parameters

string $file
Absolute file path

Returns

string
short path

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPath

wrapText()source public

wrapText( string $text , string|integer|array $options array() )

Wrap a block of text. Allows you to set the width, and indenting on a block of text.

Options

  • width The width to wrap to. Defaults to 72
  • wordWrap Only wrap on words breaks (spaces) Defaults to true.
  • indent Indent the text with the string provided. Defaults to null.

Parameters

string $text
Text the text to format.
string|integer|array $options optional array()
Array of options to use, or an integer to wrap the text to.

Returns

string
Wrapped / indented text

See

CakeText::wrap()

Link

http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapText

Methods inherited from Object

_mergeVars()source protected

_mergeVars( array $properties , string $class , boolean $normalize true )

Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'

This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.

Parameters

array $properties
The name of the properties to merge.
string $class
The class to merge the property with.
boolean $normalize optional true
Set to true to run the properties through Hash::normalize() before merging.

_set()source protected

_set( array $properties array() )

Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.

Parameters

array $properties optional array()
An associative array containing properties and corresponding values.

_stop()source protected

_stop( integer|string $status 0 )

Stop execution of the current script. Wraps exit() making testing easier.

Parameters

integer|string $status optional 0
see http://php.net/exit for values

dispatchMethod()source public

dispatchMethod( string $method , array $params array() )

Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array

Parameters

string $method
Name of the method to call
array $params optional array()
Parameter list to use when calling $method

Returns

mixed
Returns the result of the method call

log()source public

log( string $msg , integer $type LOG_ERR , null|string|array $scope null )

Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.

Parameters

string $msg
Log message
integer $type optional LOG_ERR
Error type constant. Defined in app/Config/core.php.
null|string|array $scope optional null

The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.

Returns

boolean
Success of log write

requestAction()source public

requestAction( string|array $url , array $extra array() )

Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()

Passing POST and GET data

POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.

Parameters

string|array $url

String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.

array $extra optional array()

if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.

Returns

mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


toString()source public

toString( )

Object-to-string conversion. Each class can override this method as necessary.

Returns

string
The name of this class

Properties detail

$_modelNamessource

protected array

Holds the model names

array()

$_tablessource

protected array

Holds tables found on connection.

array()

$_validationssource

protected array

Holds validation method map.

array()

$pathsource

public string

path to Model directory

null

$skipTablessource

public array

Tables to skip when running all()

array('i18n')

$taskssource

public array

tasks

array('DbConfig', 'Fixture', 'Test', 'Template')

© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.8/class-ModelTask.html