Yii Framework Class Reference

Yii Framework v1.1.1 Class Reference

All Packages

Package | Class | Description
system | Yii | Yii is a helper class serving common framework functionalities.
 | YiiBase | YiiBase is a helper class serving common framework functionalities.
system.base | CApplication | CApplication is the base class for all application classes.
 | CApplicationComponent | CApplicationComponent is the base class for application component classes.
 | CBehavior | CBehavior is a convenient base class for behavior classes.
 | CComponent | CComponent is the base class for all components.
 | CEnumerable | CEnumerable is the base class for all enumerable types.
 | CErrorEvent | CErrorEvent represents the parameter for the onError event.
 | CErrorHandler | CErrorHandler handles uncaught PHP errors and exceptions.
 | CEvent | CEvent is the base class for all event classes.
 | CException | CException represents a generic exception for all purposes.
 | CExceptionEvent | CExceptionEvent represents the parameter for the onException event.
 | CHttpException | CHttpException represents an exception caused by invalid operations of end-users.
 | CModel | CModel is the base class providing the common features needed by data model objects.
 | CModelBehavior | CModelBehavior is a base class for behaviors that are attached to a model component.
 | CModelEvent | CModelEvent class.
 | CModule | CModule is the base class for module and application classes.
 | CSecurityManager | CSecurityManager provides private keys, hashing and encryption functions.
 | CStatePersister | CStatePersister implements a file-based persistent data storage.
 | IAction | IAction is the interface that must be implemented by controller actions.
 | IApplicationComponent | IApplicationComponent is the interface that all application components must implement.
 | IAuthManager | IAuthManager interface is implemented by an auth manager application component.
 | IBehavior | IBehavior interfaces is implemented by all behavior classes.
 | IFilter | IFilter is the interface that must be implemented by action filters.
 | IStatePersister | IStatePersister is the interface that must be implemented by state persister calsses.
 | IUserIdentity | IUserIdentity interface is implemented by a user identity class.
 | IViewRenderer | IViewRenderer interface is implemented by a view renderer class.
 | IWebServiceProvider | IWebServiceProvider interface may be implemented by Web service provider classes.
 | IWebUser | IWebUser interface is implemented by a user application component.
system.caching | CApcCache | CApcCache provides APC caching in terms of an application component.
 | CCache | CCache is the base class for cache classes with different cache storage implementation.
 | CDbCache | CDbCache implements a cache application component by storing cached data in a database.
 | CDummyCache | CDummyCache is a placeholder cache component.
 | CEAcceleratorCache | CEAcceleratorCache implements a cache application module based on eaccelerator.
 | CFileCache | CFileCache provides a file-based caching mechanism.
 | CMemCache | CMemCache implements a cache application component based on memcached.
 | CMemCacheServerConfiguration | CMemCacheServerConfiguration represents the configuration data for a single memcache server.
 | CXCache | CXCache implements a cache application module based on xcache.
 | CZendDataCache | CZendDataCache implements a cache application module based on the Zend Data Cache
 | ICache | ICache is the interface that must be implemented by cache components.
 | ICacheDependency | ICacheDependency is the interface that must be implemented by cache dependency classes.
system.caching.dependencies | CCacheDependency | CCacheDependency is the base class for cache dependency classes.
 | CChainedCacheDependency | CChainedCacheDependency represents a list of cache dependencies.
 | CDbCacheDependency | CDbCacheDependency represents a dependency based on the query result of a SQL statement.
 | CDirectoryCacheDependency | CDirectoryCacheDependency represents a dependency based on change of a directory.
 | CExpressionDependency | CExpressionDependency represents a dependency based on the result of a PHP expression.
 | CFileCacheDependency | CFileCacheDependency represents a dependency based on a file's last modification time.
 | CGlobalStateCacheDependency | CGlobalStateCacheDependency represents a dependency based on a global state value.
system.collections | CAttributeCollection | CAttributeCollection implements a collection for storing attribute names and values.
 | CConfiguration | CConfiguration represents an array-based configuration.
 | CList | CList implements an integer-indexed collection class.
 | CListIterator | CListIterator implements an interator for CList.
 | CMap | CMap implements a collection that takes key-value pairs.
 | CMapIterator | CMapIterator implements an interator for CMap.
 | CQueue | CQueue implements a queue.
 | CQueueIterator | CQueueIterator implements an interator for CQueue.
 | CStack | CStack implements a stack.
 | CStackIterator | CStackIterator implements an interator for CStack.
 | CTypedList | CTypedList represents a list whose items are of the certain type.
system.console | CConsoleApplication | CConsoleApplication represents a console application.
 | CConsoleCommand | CConsoleCommand represents an executable user command.
 | CConsoleCommandRunner | CConsoleCommandRunner manages commands and executes the requested command.
 | CHelpCommand | CHelpCommand represents a console help command.
system.db | CDbCommand | CDbCommand represents an SQL statement to execute against a database.
 | CDbConnection | CDbConnection represents a connection to a database.
 | CDbDataReader | CDbDataReader represents a forward-only stream of rows from a query result set.
 | CDbException | CDbException represents an exception that is caused by some DB-related operations.
 | CDbTransaction | CDbTransaction represents a DB transaction.
system.db.ar | CActiveFinder | CActiveFinder implements eager loading and lazy loading of related active records.
 | CActiveRecord | CActiveRecord is the base class for classes representing relational data.
 | CActiveRecordBehavior | CActiveRecordBehavior is the base class for behaviors that can be attached to CActiveRecord.
 | CActiveRecordMetaData | CActiveRecordMetaData represents the meta-data for an Active Record class.
 | CActiveRelation | CActiveRelation is the base class for representing active relations that bring back related objects.
 | CBaseActiveRelation | CBaseActiveRelation is the base class for all active relations.
 | CBelongsToRelation | CBelongsToRelation represents the parameters specifying a BELONGS_TO relation.
 | CHasManyRelation | CHasManyRelation represents the parameters specifying a HAS_MANY relation.
 | CHasOneRelation | CHasOneRelation represents the parameters specifying a HAS_ONE relation.
 | CJoinElement | CJoinElement represents a tree node in the join tree created by CActiveFinder.
 | CJoinQuery | CJoinQuery represents a JOIN SQL statement.
 | CManyManyRelation | CManyManyRelation represents the parameters specifying a MANY_MANY relation.
 | CStatElement | CStatElement represents STAT join element for CActiveFinder.
 | CStatRelation | CStatRelation represents a statistical relational query.
system.db.schema | CDbColumnSchema | CDbColumnSchema class describes the column meta data of a database table.
 | CDbCommandBuilder | CDbCommandBuilder provides basic methods to create query commands for tables.
 | CDbCriteria | CDbCriteria represents a query criteria, such as conditions, ordering by, limit/offset.
 | CDbExpression | CDbExpression represents a DB expression that does not need escaping.
 | CDbSchema | CDbSchema is the base class for retrieving metadata information.
 | CDbTableSchema | CDbTableSchema is the base class for representing the metadata of a database table.
system.db.schema.mssql | CMssqlColumnSchema | CMssqlColumnSchema class describes the column meta data of a MSSQL table.
 | CMssqlCommandBuilder | CMssqlCommandBuilder provides basic methods to create query commands for tables for Mssql Servers.
 | CMssqlPdoAdapter | This is an extension of default PDO class for mssql driver only
 | CMssqlSchema | CMssqlSchema is the class for retrieving metadata information from a MS SQL Server database.
 | CMssqlTableSchema | CMssqlTableSchema represents the metadata for a MSSQL table.
system.db.schema.mysql | CMysqlColumnSchema | CMysqlColumnSchema class describes the column meta data of a MySQL table.
 | CMysqlSchema | CMysqlSchema is the class for retrieving metadata information from a MySQL database (version 4.1.x and 5.x).
 | CMysqlTableSchema | CMysqlTableSchema represents the metadata for a MySQL table.
system.db.schema.oci | COciColumnSchema | COciColumnSchema class describes the column meta data of a Oracle table.
 | COciCommandBuilder | COciCommandBuilder provides basic methods to create query commands for tables.
 | COciSchema | COciSchema is the class for retrieving metadata information from an Oracle database.
 | COciTableSchema | COciTableSchema represents the metadata for a Oracle table.
system.db.schema.pgsql | CPgsqlColumnSchema | CPgsqlColumnSchema class describes the column meta data of a PostgreSQL table.
 | CPgsqlSchema | CPgsqlSchema is the class for retrieving metadata information from a PostgreSQL database.
 | CPgsqlTableSchema | CPgsqlTable represents the metadata for a PostgreSQL table.
system.db.schema.sqlite | CSqliteColumnSchema | CSqliteColumnSchema class describes the column meta data of a SQLite table.
 | CSqliteCommandBuilder | CSqliteCommandBuilder provides basic methods to create query commands for SQLite tables.
 | CSqliteSchema | CSqliteSchema is the class for retrieving metadata information from a SQLite (2/3) database.
system.i18n | CChoiceFormat | CChoiceFormat is a helper that chooses an appropriate message based on the specified number value.
 | CDateFormatter | CDateFormatter provides date/time localization functionalities.
 | CDbMessageSource | CDbMessageSource represents a message source that stores translated messages in database.
 | CGettextMessageSource | CGettextMessageSource represents a message source that is based on GNU Gettext.
 | CLocale | CLocale represents the data relevant to a locale.
 | CMessageSource | CMessageSource is the base class for message translation repository classes.
 | CMissingTranslationEvent | CMissingTranslationEvent represents the parameter for the onMissingTranslation event.
 | CNumberFormatter | CNumberFormatter provides number localization functionalities.
 | CPhpMessageSource | CPhpMessageSource represents a message source that stores translated messages in PHP scripts.
system.i18n.gettext | CGettextFile | CGettextFile is the base class for representing a Gettext message file.
 | CGettextMoFile | CGettextMoFile represents an MO Gettext message file.
 | CGettextPoFile | CGettextPoFile represents a PO Gettext message file.
system.logging | CDbLogRoute | CDbLogRoute stores log messages in a database table.
 | CEmailLogRoute | CEmailLogRoute sends selected log messages to email addresses.
 | CFileLogRoute | CFileLogRoute records log messages in files.
 | CLogFilter | CLogFilter preprocesses the logged messages before they are handled by a log route.
 | CLogRoute | CLogRoute is the base class for all log route classes.
 | CLogRouter | CLogRouter manages log routes that record log messages in different media.
 | CLogger | CLogger records log messages in memory.
 | CProfileLogRoute | CProfileLogRoute displays the profiling results in Web page.
 | CWebLogRoute | CWebLogRoute shows the log content in Web page.
system.test | CDbFixtureManager | CDbFixtureManager manages database fixtures during tests.
 | CDbTestCase | CDbTestCase is the base class for test cases about DB-related features.
 | CTestCase | CTestCase is the base class for all test case classes.
 | CWebTestCase | CWebTestCase is the base class for Web-based functional test case classes.
system.utils | CDateTimeParser | CDateTimeParser converts a date/time string to a UNIX timestamp according to the specified pattern.
 | CFileHelper | CFileHelper provides a set of helper methods for common file system operations.
 | CFormatter | CFormatter provides a set of commonly used data formatting methods.
 | CMarkdownParser | CMarkdownParser is a wrapper of MarkdownExtra_Parser.
 | CPropertyValue | CPropertyValue is a helper class that provides static methods to convert component property values to specific types.
 | CTimestamp | CTimestamp represents a timestamp.
 | CVarDumper | CVarDumper is intended to replace the buggy PHP function var_dump and print_r.
system.validators | CBooleanValidator | CBooleanValidator validates that the attribute value is either trueValue or falseValue.
 | CCaptchaValidator | CCaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
 | CCompareValidator | CCompareValidator compares the specified attribute value with another value and validates if they are equal.
 | CDefaultValueValidator | CDefaultValueValidator sets the attributes with the specified value.
 | CEmailValidator | CEmailValidator validates that the attribute value is a valid email address.
 | CExistValidator | CExistValidator validates that the attribute value exists in a table.
 | CFileValidator | CFileValidator verifies if an attribute is receiving a valid uploaded file.
 | CFilterValidator | CFilterValidator transforms the data being validated based on a filter.
 | CInlineValidator | CInlineValidator represents a validator which is defined as a method in the object being validated.
 | CNumberValidator | CNumberValidator validates that the attribute value is a number.
 | CRangeValidator | CRangeValidator validates that the attribute value is among the list (specified via range).
 | CRegularExpressionValidator | CRegularExpressionValidator validates that the attribute value matches to the specified regular expression.
 | CRequiredValidator | CRequiredValidator validates that the specified attribute does not have null or empty value.
 | CSafeValidator | CSafeValidator marks the associated attributes to be safe for massive assignments.
 | CStringValidator | CStringValidator validates that the attribute value is of certain length.
 | CTypeValidator | CTypeValidator verifies if the attribute is of the type specified by type.
 | CUniqueValidator | CUniqueValidator validates that the attribute value is unique in the corresponding database table.
 | CUnsafeValidator | CUnsafeValidator marks the associated attributes to be unsafe so that they cannot be massively assigned.
 | CUrlValidator | CUrlValidator validates that the attribute value is a valid http or https URL.
 | CValidator | CValidator is the base class for all validators.
system.web | CActiveDataProvider | CActiveDataProvider implements a data provider based on ActiveRecord.
 | CAssetManager | CAssetManager is a Web application component that manages private files (called assets) and makes them accessible by Web clients.
 | CBaseController | CBaseController is the base class for CController and CWidget.
 | CCacheHttpSession | CCacheHttpSession implements a session component using cache as storage medium.
 | CClientScript | CClientScript manages JavaScript and CSS stylesheets for views.
 | CController | CController manages a set of actions which deal with the corresponding user requests.
 | CCookieCollection | CCookieCollection implements a collection class to store cookies.
 | CDataProvider | CDataProvider is a base class that implements the IDataProvider interface.
 | CDbHttpSession | CDbHttpSession extends CHttpSession by using database as session data storage.
 | CExtController | CExtController is the base class for controllers distributed as extension.
 | CFormModel | CFormModel represents a data model that collects HTML form inputs.
 | CHttpCookie | A CHttpCookie instance stores a single cookie, including the cookie name, value, domain, path, expire, and secure.
 | CHttpRequest | CHttpRequest encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
 | CHttpSession | CHttpSession provides session-level data management and the related configurations.
 | CHttpSessionIterator | CHttpSessionIterator implements an interator for CHttpSession.
 | COutputEvent | COutputEvent represents the parameter for events related with output handling.
 | CPagination | CPagination represents information relevant to pagination.
 | CSort | CSort represents information relevant to sorting.
 | CTheme | CTheme represents an application theme.
 | CThemeManager | CThemeManager manages the themes for the Web application.
 | CUploadedFile | CUploadedFile represents the information for an uploaded file.
 | CUrlManager | CUrlManager manages the URLs of Yii Web applications.
 | CUrlRule | CUrlRule represents a URL formatting/parsing rule.
 | CWebApplication | CWebApplication extends CApplication by providing functionalities specific to Web requests.
 | CWebModule | CWebModule represents an application module.
 | CWidgetFactory | CWidgetFactory creates new widgets to be used in views.
 | IDataProvider | IDataProvider is the interface that must be implemented by data provider classes.
 | IWidgetFactory | IWidgetFactory is the interface that must be implemented by a widget factory class.
system.web.actions | CAction | CAction is the base class for all controller action classes.
 | CInlineAction | CInlineAction represents an action that is defined as a controller method.
 | CViewAction | CViewAction represents an action that displays a view according to a user-specified parameter.
system.web.auth | CAccessControlFilter | CAccessControlFilter performs authorization checks for the specified actions.
 | CAccessRule | CAccessRule represents an access rule that is managed by CAccessControlFilter.
 | CAuthAssignment | CAuthAssignment represents an assignment of a role to a user.
 | CAuthItem | CAuthItem represents an authorization item.
 | CAuthManager | CAuthManager is the base class for authorization manager classes.
 | CBaseUserIdentity | CBaseUserIdentity is a base class implementing IUserIdentity.
 | CDbAuthManager | CDbAuthManager represents an authorization manager that stores authorization information in database.
 | CPhpAuthManager | CPhpAuthManager represents an authorization manager that stores authorization information in terms of a PHP script file.
 | CUserIdentity | CUserIdentity is a base class for representing identities that are authenticated based on a username and a password.
 | CWebUser | CWebUser represents the persistent state for a Web application user.
system.web.filters | CFilter | CFilter is the base class for all filters.
 | CFilterChain | CFilterChain represents a list of filters being applied to an action.
 | CInlineFilter | CInlineFilter represents a filter defined as a controller method.
system.web.form | CForm | CForm represents a form object that contains form input specifications.
 | CFormButtonElement | CFormButtonElement represents a form button element.
 | CFormElement | CFormElement is the base class for presenting all kinds of form element.
 | CFormElementCollection | CFormElementCollection implements the collection for storing form elements.
 | CFormInputElement | CFormInputElement represents form input element.
 | CFormStringElement | CFormStringElement represents a string in a form.
system.web.helpers | CGoogleApi | CGoogleApi provides helper methods to easily access Google AJAX APIs.
 | CHtml | CHtml is a static class that provides a collection of helper methods for creating HTML views.
 | CJSON | CJSON converts PHP data to and from JSON format.
 | CJavaScript | CJavaScript is a helper class containing JavaScript-related handling functions.
system.web.renderers | CPradoViewRenderer | CPradoViewRenderer implements a view renderer that allows users to use a template syntax similar to PRADO templates.
 | CViewRenderer | CViewRenderer is the base class for view renderer classes.
system.web.services | CSoapObjectWrapper | CSoapObjectWrapper is a wrapper class internally used when SoapServer::setObject() is not defined.
 | CWebService | CWebService encapsulates SoapServer and provides a WSDL-based web service.
 | CWebServiceAction | CWebServiceAction implements an action that provides Web services.
 | CWsdlGenerator | CWsdlGenerator generates the WSDL for a given service class.
system.web.widgets | CActiveForm | CActiveForm provides a set of methods that can facilitate creating a form associated with some data models.
 | CAutoComplete | CAutoComplete generates an auto-complete text field.
 | CClipWidget | CClipWidget records its content and makes it available elsewhere.
 | CContentDecorator | CContentDecorator decorates the content it encloses with the specified view.
 | CFilterWidget | CFilterWidget is the base class for widgets that can also be used as filters.
 | CFlexWidget | CFlexWidget embeds a Flex 3.x application into a page.
 | CHtmlPurifier | CHtmlPurifier is wrapper of HTML Purifier.
 | CInputWidget | CInputWidget is the base class for widgets that collect user inputs.
 | CMarkdown | CMarkdown converts the captured content from markdown syntax to HTML code.
 | CMaskedTextField | CMaskedTextField generates a masked text field.
 | CMultiFileUpload | CMultiFileUpload generates a file input that can allow uploading multiple files at a time.
 | COutputCache | COutputCache enables caching the output generated by an action or a view fragment.
 | COutputProcessor | COutputProcessor transforms the content into a different format.
 | CStarRating | CStarRating displays a star rating control that can collect user rating input.
 | CTabView | CTabView displays contents in multiple tabs.
 | CTextHighlighter | CTextHighlighter does syntax highlighting for its body content.
 | CTreeView | CTreeView displays a tree view of hierarchical data.
 | CWidget | CWidget is the base class for widgets.
system.web.widgets.captcha | CCaptcha | CCaptcha renders a CAPTCHA image element.
 | CCaptchaAction | CCaptchaAction renders a CAPTCHA image.
system.web.widgets.pagers | CBasePager | CBasePager is the base class for all pagers.
 | CLinkPager | CLinkPager displays a list of hyperlinks that lead to different pages of target.
 | CListPager | CListPager displays a dropdown list that contains options leading to different pages of target.
zii.behaviors | CTimestampBehavior | CTimestampBehavior will automatically fill date and time related atributes.
zii.widgets | CBaseListView | CBaseListView is the base class for CListView and CGridView.
 | CBreadcrumbs | CBreadcrumbs displays a list of links indicating the position of the current page in the whole website.
 | CDetailView | CDetailView displays the detail of a single data model.
 | CListView | CListView displays a list of data items in terms of a list.
 | CMenu | CMenu displays a multi-level menu using nested HTML lists.
 | CPortlet | CPortlet is the base class for portlet widgets.
zii.widgets.grid | CButtonColumn | CButtonColumn represents a grid view column that renders one or several buttons.
 | CCheckBoxColumn | CCheckBoxColumn represents a grid view column of checkboxes.
 | CDataColumn | CDataColumn represents a grid view column that is associated with a data attribute or expression.
 | CGridColumn | CGridColumn is the base class for all grid view column classes.
 | CGridView | CGridView displays a list of data items in terms of a table.
 | CLinkColumn | CLinkColumn represents a grid view column that renders a hyperlink in each of its data cells.
zii.widgets.jui | CJuiAccordion | CJuiAccordion displays an accordion widget.
 | CJuiDatePicker | CJuiDatePicker displays a datepicker.
 | CJuiDialog | CJuiDialog displays a dialog widget.
 | CJuiDraggable | CJuiDraggable displays a draggable widget.
 | CJuiDroppable | CJuiDroppable displays a droppable widget.
 | CJuiInputWidget | CJuiInputWidget is the base class for JUI widgets that can collect user input.
 | CJuiProgressBar | CJuiProgressBar displays a progress bar widget.
 | CJuiResizable | CJuiResizable displays a resizable widget.
 | CJuiSelectable | CJuiSelectable displays an accordion widget.
 | CJuiSlider | CJuiSlider displays a slider.
 | CJuiSliderInput | CJuiSliderInput displays a slider. It can be used in forms and post its value.
 | CJuiSortable | CJuiSortable displays an accordion widget.
 | CJuiTabs | CJuiTabs displays a tabs widget.
 | CJuiWidget | This is the base class for all JUI widget classes.
Copyright © 2008-2010 by Yii Software LLC
All Rights Reserved.


Yii

All Packages | Methods
Package | system
Inheritance | class Yii » YiiBase
Since | 1.0
Version | $Id: yii.php 1678 2010-01-07 21:02:00Z qiang.xue $
Yii is a helper class serving common framework functionalities.

It encapsulates YiiBase which provides the actual implementation. By writing your own Yii class, you can customize some functionalities of YiiBase.

Public Methods

Hide inherited methods

Method | Description | Defined By
app() |  | YiiBase
autoload() | Class autoload loader. | YiiBase
beginProfile() | Marks the begin of a code block for profiling. | YiiBase
createApplication() | Creates an application of the specified class. | YiiBase
createComponent() | Creates an object and initializes it based on the given configuration. | YiiBase
createConsoleApplication() | Creates a console application instance. | YiiBase
createWebApplication() | Creates a Web application instance. | YiiBase
endProfile() | Marks the end of a code block for profiling. | YiiBase
getFrameworkPath() |  | YiiBase
getLogger() |  | YiiBase
getPathOfAlias() | Translates an alias into a file path. | YiiBase
getVersion() |  | YiiBase
import() | Imports the definition of a class or a directory of class files. | YiiBase
log() | Logs a message. | YiiBase
powered() |  | YiiBase
registerAutoloader() | Registers a new class autoloader. | YiiBase
setApplication() | Stores the application instance in the class static member. | YiiBase
setPathOfAlias() | Create a path alias. | YiiBase
t() | Translates a message to the specified language. | YiiBase
trace() | Writes a trace message. | YiiBase


YiiBase

All Packages | Methods
Package | system
Inheritance | class YiiBase
Subclasses | Yii
Since | 1.0
Version | $Id: YiiBase.php 1903 2010-03-14 04:27:02Z qiang.xue $
YiiBase is a helper class serving common framework functionalities.

Do not use YiiBase directly. Instead, use its child class Yii where you can customize methods of YiiBase.

Public Methods

Hide inherited methods

Method | Description | Defined By
app() |  | YiiBase
autoload() | Class autoload loader. | YiiBase
beginProfile() | Marks the begin of a code block for profiling. | YiiBase
createApplication() | Creates an application of the specified class. | YiiBase
createComponent() | Creates an object and initializes it based on the given configuration. | YiiBase
createConsoleApplication() | Creates a console application instance. | YiiBase
createWebApplication() | Creates a Web application instance. | YiiBase
endProfile() | Marks the end of a code block for profiling. | YiiBase
getFrameworkPath() |  | YiiBase
getLogger() |  | YiiBase
getPathOfAlias() | Translates an alias into a file path. | YiiBase
getVersion() |  | YiiBase
import() | Imports the definition of a class or a directory of class files. | YiiBase
log() | Logs a message. | YiiBase
powered() |  | YiiBase
registerAutoloader() | Registers a new class autoloader. | YiiBase
setApplication() | Stores the application instance in the class static member. | YiiBase
setPathOfAlias() | Create a path alias. | YiiBase
t() | Translates a message to the specified language. | YiiBase
trace() | Writes a trace message. | YiiBase

Method Details

app() method
public static CApplication app()
{return} CApplication the application singleton, null if the singleton has not been created yet.

autoload() method
public static boolean autoload(string $className)
$className | string | class name
{return} | boolean | whether the class has been loaded successfully

Class autoload loader. This method is provided to be invoked within an __autoload() magic method.

beginProfile() method
public static void beginProfile(string $token, string $category='application')
$token | string | token for the code block
$category | string | the category of this log message

Marks the begin of a code block for profiling. This has to be matched with a call to endProfile() with the same token. The begin- and end- calls must also be properly nested, e.g.,

Yii::beginProfile('block1');
Yii::beginProfile('block2');
Yii::endProfile('block2');
Yii::endProfile('block1');
The following sequence is not valid:
Yii::beginProfile('block1');
Yii::beginProfile('block2');
Yii::endProfile('block1');
Yii::endProfile('block2');

See Also

  • endProfile
createApplication() method (available since v1.0.10)
public static mixed createApplication(string $class, mixed $config=NULL)
$class | string | the application class name
$config | mixed | application configuration. This parameter will be passed as the parameter to the constructor of the application class.
{return} | mixed | the application instance

Creates an application of the specified class.

createComponent() method
public static mixed createComponent(mixed $config)
$config | mixed | the configuration. It can be either a string or an array.
{return} | mixed | the created object

Creates an object and initializes it based on the given configuration.

The specified configuration can be either a string or an array. If the former, the string is treated as the object type which can be either the class name or class path alias. If the latter, the 'class' element is treated as the object type, and the rest name-value pairs in the array are used to initialize the corresponding object properties.

Any additional parameters passed to this method will be passed to the constructor of the object being created.

NOTE: the array-typed configuration has been supported since version 1.0.1.

createConsoleApplication() method
public static void createConsoleApplication(mixed $config=NULL)
$config mixed application configuration. If a string, it is treated as the path of the file that contains the configuration; If an array, it is the actual configuration information. Please make sure you specify the basePath property in the configuration, which should point to the directory containing all application logic, template and data. If not, the directory will be defaulted to 'protected'.

Creates a console application instance.

createWebApplication() method
public static void createWebApplication(mixed $config=NULL)
$config mixed application configuration. If a string, it is treated as the path of the file that contains the configuration; If an array, it is the actual configuration information. Please make sure you specify the basePath property in the configuration, which should point to the directory containing all application logic, template and data. If not, the directory will be defaulted to 'protected'.

Creates a Web application instance.

endProfile() method
public static void endProfile(string $token, string $category='application')
$token | string | token for the code block
$category | string | the category of this log message

Marks the end of a code block for profiling. This has to be matched with a previous call to beginProfile() with the same token.

See Also

  • beginProfile
getFrameworkPath() method
public static string getFrameworkPath()
{return} string the path of the framework

getLogger() method
public static CLogger getLogger()
{return} CLogger message logger

getPathOfAlias() method
public static mixed getPathOfAlias(string $alias)
$alias | string | alias (e.g. system.web.CController)
{return} | mixed | file path corresponding to the alias, false if the alias is invalid.

Translates an alias into a file path. Note, this method does not ensure the existence of the resulting file path. It only checks if the root alias is valid or not.

getVersion() method
public static string getVersion()
{return} string the version of Yii framework

import() method
public static string import(string $alias, boolean $forceInclude=false)
$alias | string | path alias to be imported
$forceInclude | boolean | whether to include the class file immediately. If false, the class file will be included only when the class is being used.
{return} | string | the class name or the directory that this alias refers to

Imports the definition of a class or a directory of class files.

Path aliases are used to refer to the class file or directory being imported. If importing a path alias ending with '.*', the alias is considered as a directory which will be added to the PHP include paths; Otherwise, the alias is translated to the path of a class file which is included when needed.

For example, importing 'system.web.*' will add the 'web' directory of the framework to the PHP include paths; while importing 'system.web.CController' will include the class file 'web/CController.php' when needed.

The same alias can be imported multiple times, but only the first time is effective.

log() method
public static void log(string $msg, string $level='info', string $category='application')
$msg | string | message to be logged
$level | string | level of the message (e.g. 'trace', 'warning', 'error'). It is case-insensitive.
$category | string | category of the message (e.g. 'system.web'). It is case-insensitive.

Logs a message. Messages logged by this method may be retrieved via CLogger::getLogs and may be recorded in different media, such as file, email, database, using CLogRouter.

powered() method
public static string powered()
{return} string a string that can be displayed on your Web page showing Powered-by-Yii information

registerAutoloader() method (available since v1.0.10)
public static void registerAutoloader(callback $callback)
$callback callback a valid PHP callback (function name or array($className,$methodName)).

Registers a new class autoloader. The new autoloader will be placed before autoload and after any other existing autoloaders.

setApplication() method
public static void setApplication(CApplication $app)
$app CApplication the application instance. If this is null, the existing application singleton will be removed.

Stores the application instance in the class static member. This method helps implement a singleton pattern for CApplication. Repeated invocation of this method or the CApplication constructor will cause the throw of an exception. To retrieve the application instance, use app().

setPathOfAlias() method
public static void setPathOfAlias(string $alias, string $path)
$alias | string | alias to the path
$path | string | the path corresponding to the alias. If this is null, the corresponding path alias will be removed.

Create a path alias. Note, this method neither checks the existence of the path nor normalizes the path.

t() method
public static string t(string $category, string $message, array $params=array ( ), string $source=NULL, string $language=NULL)
$category | string | message category. Please use only word letters. Note, category 'yii' is reserved for Yii framework core code use. See CPhpMessageSource for more interpretation about message category.
$message | string | the original message
$params | array | parameters to be applied to the message using strtr. Starting from version 1.0.2, the first parameter can be a number without key. And in this case, the method will call CChoiceFormat::format to choose an appropriate message translation.
$source | string | which message source application component to use. Defaults to null, meaning using 'coreMessages' for messages belonging to the 'yii' category and using 'messages' for the rest messages.
$language | string | the target language. If null (default), the application language will be used. This parameter has been available since version 1.0.3.
{return} | string | the translated message

Translates a message to the specified language. Starting from version 1.0.2, this method supports choice format (see CChoiceFormat), i.e., the message returned will be chosen from a few candidates according to the given number value. This feature is mainly used to solve plural format issue in case a message has different plural forms in some languages.

See Also

  • CMessageSource
trace() method
public static void trace(string $msg, string $category='application')
$msg | string | message to be logged
$category | string | category of the message

Writes a trace message. This method will only log a message when the application is in debug mode.

See Also

  • log


CApplication

All Packages | Properties | Methods | Events
Package | system.base
Inheritance | abstract class CApplication » CModule » CComponent
Subclasses | CConsoleApplication, CWebApplication
Since | 1.0
Version | $Id: CApplication.php 1789 2010-02-02 18:38:56Z qiang.xue $
CApplication is the base class for all application classes.

An application serves as the global context that the user request is being processed. It manages a set of application components that provide specific functionalities to the whole application.

The core application components provided by CApplication are the following:
  • errorHandler: handles PHP errors and uncaught exceptions. This application component is dynamically loaded when needed.
  • securityManager: provides security-related services, such as hashing, encryption. This application component is dynamically loaded when needed.
  • statePersister: provides global state persistence method. This application component is dynamically loaded when needed.
  • cache: provides caching feature. This application component is disabled by default.
  • messages: provides the message source for translating application messages. This application component is dynamically loaded when needed.
  • coreMessages: provides the message source for translating Yii framework messages. This application component is dynamically loaded when needed.

CApplication will undergo the following lifecycles when processing a user request:
  1. load application configuration;
  2. set up class autoloader and error handling;
  3. load static application components;
  4. onBeginRequest: preprocess the user request;
  5. processRequest: process the user request;
  6. onEndRequest: postprocess the user request;

Starting from lifecycle 3, if a PHP error or an uncaught exception occurs, the application will switch to its error handling logic and jump to step 6 afterwards.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the root directory of the application. | CApplication
behaviors | array | the behaviors that should be attached to the module. | CModule
cache | CCache | the cache application component. | CApplication
charset | string | the charset currently used for the application. | CApplication
components | array | the currently loaded components (indexed by their IDs) | CModule
coreMessages | CPhpMessageSource | the core message translations | CApplication
dateFormatter | CDateFormatter | the locale-dependent date formatter. | CApplication
db | CDbConnection | the database connection | CApplication
errorHandler | CErrorHandler | the error handler application component. | CApplication
extensionPath | string | Returns the root directory that holds all third-party extensions. | CApplication
id | string | a unique identifier for the application. | CApplication
language | string | the language that the user is using and the application should be targeted to. | CApplication
locale | CLocale | the locale instance | CApplication
localeDataPath | string | the directory that contains the locale data. | CApplication
messages | CMessageSource | the application message translations | CApplication
modulePath | string | the directory that contains the application modules. | CModule
modules | array | the configuration of the currently installed modules (module ID => configuration) | CModule
name | string | the application name. | CApplication
numberFormatter | CNumberFormatter | the locale-dependent number formatter. | CApplication
params | CAttributeCollection | the list of user-defined parameters | CModule
parentModule | CModule | the parent module. | CModule
preload | array | the IDs of the application components that should be preloaded. | CModule
request | CHttpRequest | the request component | CApplication
runtimePath | string | the directory that stores runtime files. | CApplication
securityManager | CSecurityManager | the security manager application component. | CApplication
sourceLanguage | string | the language that the application is written in. | CApplication
statePersister | CStatePersister | the state persister application component. | CApplication
timeZone | string | Returns the time zone used by this application. | CApplication
urlManager | CUrlManager | the URL manager component | CApplication

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CApplication
__get() | Getter magic method. | CModule
__isset() | Checks if a property value is null. | CModule
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearGlobalState() | Clears a global value. | CApplication
configure() | Configures the module with the specified configuration. | CModule
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
displayError() | Displays the captured PHP error. | CApplication
displayException() | Displays the uncaught PHP exception. | CApplication
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
end() | Terminates the application. | CApplication
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
findLocalizedFile() | Returns the localized version of a specified file. | CApplication
getBasePath() |  | CApplication
getCache() |  | CApplication
getComponent() | Retrieves the named application component. | CModule
getComponents() |  | CModule
getCoreMessages() |  | CApplication
getDateFormatter() |  | CApplication
getDb() |  | CApplication
getErrorHandler() |  | CApplication
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getExtensionPath() | Returns the root directory that holds all third-party extensions. | CApplication
getGlobalState() | Returns a global value. | CApplication
getId() |  | CApplication
getLanguage() |  | CApplication
getLocale() |  | CApplication
getLocaleDataPath() |  | CApplication
getMessages() |  | CApplication
getModule() | Retrieves the named application module. | CModule
getModulePath() |  | CModule
getModules() |  | CModule
getNumberFormatter() |  | CApplication
getParams() |  | CModule
getParentModule() |  | CModule
getRequest() |  | CApplication
getRuntimePath() |  | CApplication
getSecurityManager() |  | CApplication
getStatePersister() |  | CApplication
getTimeZone() | Returns the time zone used by this application. | CApplication
getUrlManager() |  | CApplication
handleError() | Handles PHP execution errors such as warnings, notices. | CApplication
handleException() | Handles uncaught PHP exceptions. | CApplication
hasComponent() |  | CModule
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
onBeginRequest() | Raised right BEFORE the application processes the request. | CApplication
onEndRequest() | Raised right AFTER the application processes the request. | CApplication
onError() | Raised when a PHP execution error occurs. | CApplication
onException() | Raised when an uncaught PHP exception occurs. | CApplication
processRequest() | Processes the request. | CApplication
raiseEvent() | Raises an event. | CComponent
run() | Runs the application. | CApplication
setAliases() | Defines the root aliases. | CModule
setBasePath() | Sets the root directory of the application. | CApplication
setComponent() | Puts a component under the management of the module. | CModule
setComponents() | Sets the application components. | CModule
setExtensionPath() |  | CApplication
setGlobalState() | Sets a global value. | CApplication
setId() |  | CApplication
setImport() | Sets the aliases that are used in the module. | CModule
setLanguage() | Specifies which language the application is targeted to. | CApplication
setLocaleDataPath() |  | CApplication
setModulePath() |  | CModule
setModules() | Configures the sub-modules of this module. | CModule
setParams() |  | CModule
setRuntimePath() |  | CApplication
setTimeZone() | Sets the time zone used by this application. | CApplication

Protected Methods

Hide inherited methods

Method | Description | Defined By
init() | Initializes the module. | CModule
initSystemHandlers() | Initializes the class autoloader and error handlers. | CApplication
loadGlobalState() | Loads the global state data from persistent storage. | CApplication
preinit() | Preinitializes the module. | CModule
preloadComponents() | Loads static application components. | CModule
registerCoreComponents() | Registers the core application components. | CApplication
saveGlobalState() | Saves the global state data into persistent storage. | CApplication

Events

Hide inherited events

Event | Description | Defined By
onBeginRequest | Raised right BEFORE the application processes the request. | CApplication
onEndRequest | Raised right AFTER the application processes the request. | CApplication
onException | Raised when an uncaught PHP exception occurs. | CApplication
onError | Raised when a PHP execution error occurs. | CApplication

Property Details

basePath property
public string getBasePath()
public void setBasePath(string $path)

the root directory of the application. Defaults to 'protected'.

cache property read-only
public CCache getCache()

the cache application component. Null if the component is not enabled.

charset property
public string $charset;

the charset currently used for the application. Defaults to 'UTF-8'.

coreMessages property read-only
public CPhpMessageSource getCoreMessages()

the core message translations

dateFormatter property read-only
public CDateFormatter getDateFormatter()

the locale-dependent date formatter. The current application locale will be used.

db property read-only
public CDbConnection getDb()

the database connection

errorHandler property read-only
public CErrorHandler getErrorHandler()

the error handler application component.

extensionPath property
public string getExtensionPath()
public void setExtensionPath(string $path)

Returns the root directory that holds all third-party extensions.

id property
public string getId()
public void setId(string $id)

a unique identifier for the application.

language property
public string getLanguage()
public void setLanguage(string $language)

the language that the user is using and the application should be targeted to. Defaults to the source language.

locale property read-only
public CLocale getLocale(string $localeID=NULL)

the locale instance

localeDataPath property (available since v1.1.0)
public string getLocaleDataPath()
public void setLocaleDataPath(string $value)

the directory that contains the locale data. It defaults to 'framework/i18n/data'.

messages property read-only
public CMessageSource getMessages()

the application message translations

name property
public string $name;

the application name. Defaults to 'My Application'.

numberFormatter property read-only
public CNumberFormatter getNumberFormatter()

the locale-dependent number formatter. The current application locale will be used.

request property read-only
public CHttpRequest getRequest()

the request component

runtimePath property
public string getRuntimePath()
public void setRuntimePath(string $path)

the directory that stores runtime files. Defaults to 'protected/runtime'.

securityManager property read-only
public CSecurityManager getSecurityManager()

the security manager application component.

sourceLanguage property
public string $sourceLanguage;

the language that the application is written in. This mainly refers to the language that the messages and view files are in. Defaults to 'en_us' (US English).

statePersister property read-only
public CStatePersister getStatePersister()

the state persister application component.

timeZone property (available since v1.0.9)
public string getTimeZone()
public void setTimeZone(string $value)

Returns the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_get().

See Also

  • http://php.net/manual/en/function.date-default-timezone-get.php
urlManager property read-only
public CUrlManager getUrlManager()

the URL manager component

Method Details

__construct() method
public void __construct(mixed $config=NULL)
$config mixed application configuration. If a string, it is treated as the path of the file that contains the configuration; If an array, it is the actual configuration information. Please make sure you specify the basePath property in the configuration, which should point to the directory containing all application logic, template and data. If not, the directory will be defaulted to 'protected'.

Constructor.

clearGlobalState() method
public void clearGlobalState(string $key)
$key string the name of the value to be cleared

Clears a global value.

The value cleared will no longer be available in this request and the following requests.

displayError() method
public void displayError(integer $code, string $message, string $file, string $line)
$code | integer | error code
$message | string | error message
$file | string | error file
$line | string | error line

Displays the captured PHP error. This method displays the error in HTML when there is no active error handler.

displayException() method
public void displayException(Exception $exception)
$exception Exception the uncaught exception

Displays the uncaught PHP exception. This method displays the exception in HTML when there is no active error handler.

end() method
public void end(integer $status=0)
$status integer exit status (value 0 means normal exit while other values mean abnormal exit).

Terminates the application. This method replaces PHP's exit() function by calling onEndRequest before exiting.

findLocalizedFile() method
public string findLocalizedFile(string $srcFile, string $srcLanguage=NULL, string $language=NULL)
$srcFile | string | the original file
$srcLanguage | string | the language that the original file is in. If null, the application source language is used.
$language | string | the desired language that the file should be localized to. If null, the application language will be used.
{return} | string | the matching localized file. The original file is returned if no localized version is found or if source language is the same as the desired language.

Returns the localized version of a specified file.

The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory named as the locale ID. For example, given the file "path/to/view.php" and locale ID "zh_cn", the localized file will be looked for as "path/to/zh_cn/view.php". If the file is not found, the original file will be returned.

For consistency, it is recommended that the locale ID is given in lower case and in the format of LanguageID_RegionID (e.g. "en_us").

getBasePath() method
public string getBasePath()
{return} string the root directory of the application. Defaults to 'protected'.

getCache() method
public CCache getCache()
{return} CCache the cache application component. Null if the component is not enabled.

getCoreMessages() method
public CPhpMessageSource getCoreMessages()
{return} CPhpMessageSource the core message translations

getDateFormatter() method
public CDateFormatter getDateFormatter()
{return} CDateFormatter the locale-dependent date formatter. The current application locale will be used.

getDb() method
public CDbConnection getDb()
{return} CDbConnection the database connection

getErrorHandler() method
public CErrorHandler getErrorHandler()
{return} CErrorHandler the error handler application component.

getExtensionPath() method
public string getExtensionPath()
{return} string the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.

Returns the root directory that holds all third-party extensions.

getGlobalState() method
public mixed getGlobalState(string $key, mixed $defaultValue=NULL)
$key | string | the name of the value to be returned
$defaultValue | mixed | the default value. If the named global value is not found, this will be returned instead.
{return} | mixed | the named global value

Returns a global value.

A global value is one that is persistent across users sessions and requests.

See Also

  • setGlobalState
getId() method
public string getId()
{return} string a unique identifier for the application.

getLanguage() method
public string getLanguage()
{return} string the language that the user is using and the application should be targeted to. Defaults to the source language.

getLocale() method
public CLocale getLocale(string $localeID=NULL)
$localeID | string | locale ID (e.g. en_US). If null, the application language ID will be used.
{return} | CLocale | the locale instance

getLocaleDataPath() method (available since v1.1.0)
public string getLocaleDataPath()
{return} string the directory that contains the locale data. It defaults to 'framework/i18n/data'.

getMessages() method
public CMessageSource getMessages()
{return} CMessageSource the application message translations

getNumberFormatter() method
public CNumberFormatter getNumberFormatter()
{return} CNumberFormatter the locale-dependent number formatter. The current application locale will be used.

getRequest() method
public CHttpRequest getRequest()
{return} CHttpRequest the request component

getRuntimePath() method
public string getRuntimePath()
{return} string the directory that stores runtime files. Defaults to 'protected/runtime'.

getSecurityManager() method
public CSecurityManager getSecurityManager()
{return} CSecurityManager the security manager application component.

getStatePersister() method
public CStatePersister getStatePersister()
{return} CStatePersister the state persister application component.

getTimeZone() method (available since v1.0.9)
public string getTimeZone()
{return} string the time zone used by this application.

Returns the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_get().

See Also

  • http://php.net/manual/en/function.date-default-timezone-get.php
getUrlManager() method
public CUrlManager getUrlManager()
{return} CUrlManager the URL manager component

handleError() method
public void handleError(integer $code, string $message, string $file, integer $line)
$code | integer | the level of the error raised
$message | string | the error message
$file | string | the filename that the error was raised in
$line | integer | the line number the error was raised at

Handles PHP execution errors such as warnings, notices.

This method is implemented as a PHP error handler. It requires that constant YII_ENABLE_ERROR_HANDLER be defined true.

This method will first raise an onError event. If the error is not handled by any event handler, it will call errorHandler to process the error.

The application will be terminated by this method.

handleException() method
public void handleException(Exception $exception)
$exception Exception exception that is not caught

Handles uncaught PHP exceptions.

This method is implemented as a PHP exception handler. It requires that constant YII_ENABLE_EXCEPTION_HANDLER be defined true.

This method will first raise an onException event. If the exception is not handled by any event handler, it will call errorHandler to process the exception.

The application will be terminated by this method.

initSystemHandlers() method
protected void initSystemHandlers()

Initializes the class autoloader and error handlers.

loadGlobalState() method
protected void loadGlobalState()

Loads the global state data from persistent storage.

See Also

  • getStatePersister
onBeginRequest() method
public void onBeginRequest(CEvent $event)
$event CEvent the event parameter

Raised right BEFORE the application processes the request.

onEndRequest() method
public void onEndRequest(CEvent $event)
$event CEvent the event parameter

Raised right AFTER the application processes the request.

onError() method
public void onError(CErrorEvent $event)
$event CErrorEvent event parameter

Raised when a PHP execution error occurs.

An event handler can set the handled property of the event parameter to be true to indicate no further error handling is needed. Otherwise, the errorHandler application component will continue processing the error.

onException() method
public void onException(CExceptionEvent $event)
$event CExceptionEvent event parameter

Raised when an uncaught PHP exception occurs.

An event handler can set the handled property of the event parameter to be true to indicate no further error handling is needed. Otherwise, the errorHandler application component will continue processing the error.

processRequest() method
abstract public void processRequest()

Processes the request. This is the place where the actual request processing work is done. Derived classes should override this method.

registerCoreComponents() method
protected void registerCoreComponents()

Registers the core application components.

See Also

  • setComponents
run() method
public void run()

Runs the application. This method loads static application components. Derived classes usually overrides this method to do more application-specific tasks. Remember to call the parent implementation so that static application components are loaded.

saveGlobalState() method
protected void saveGlobalState()

Saves the global state data into persistent storage.

See Also

  • getStatePersister
setBasePath() method
public void setBasePath(string $path)
$path string the root directory of the application.

Sets the root directory of the application. This method can only be invoked at the begin of the constructor.

setExtensionPath() method
public void setExtensionPath(string $path)
$path string the directory that contains all third-party extensions.

setGlobalState() method
public void setGlobalState(string $key, mixed $value, mixed $defaultValue=NULL)
$key | string | the name of the value to be saved
$value | mixed | the global value to be saved. It must be serializable.
$defaultValue | mixed | the default value. If the named global value is the same as this value, it will be cleared from the current storage.

Sets a global value.

A global value is one that is persistent across users sessions and requests. Make sure that the value is serializable and unserializable.

See Also

  • getGlobalState
setId() method
public void setId(string $id)
$id string a unique identifier for the application.

setLanguage() method
public void setLanguage(string $language)
$language string the user language (e.g. 'en_US', 'zh_CN'). If it is null, the sourceLanguage will be used.

Specifies which language the application is targeted to.

This is the language that the application displays to end users. If set null, it uses the source language.

Unless your application needs to support multiple languages, you should always set this language to null to maximize the application's performance.

setLocaleDataPath() method (available since v1.1.0)
public void setLocaleDataPath(string $value)
$value string the directory that contains the locale data.

setRuntimePath() method
public void setRuntimePath(string $path)
$path string the directory that stores runtime files.

setTimeZone() method (available since v1.0.9)
public void setTimeZone(string $value)
$value string the time zone used by this application.

Sets the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_set().

See Also

  • http://php.net/manual/en/function.date-default-timezone-set.php


CApplicationComponent

All Packages | Properties | Methods
Package | system.base
Inheritance | abstract class CApplicationComponent » CComponent
Implements | IApplicationComponent
Subclasses | CAssetManager, CAuthManager, CCache, CClientScript, CDbConnection, CDbFixtureManager, CDummyCache, CErrorHandler, CFormatter, CHttpRequest, CHttpSession, CLogRouter, CMessageSource, CSecurityManager, CStatePersister, CThemeManager, CUrlManager, CViewRenderer, CWebUser, CWidgetFactory
Since | 1.0
Version | $Id: CApplicationComponent.php 1678 2010-01-07 21:02:00Z qiang.xue $
CApplicationComponent is the base class for application component classes.

CApplicationComponent implements the basic methods required by IApplicationComponent.

When developing an application component, try to put application component initialization code in the init() method instead of the constructor. This has the advantage that the application component can be customized through application configuration.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent

Property Details

behaviors property (available since v1.0.2)
public array $behaviors;

the behaviors that should be attached to this component. The behaviors will be attached to the component when init is called. Please refer to CModel::behaviors on how to specify the value of this property.

isInitialized property read-only
public boolean getIsInitialized()

whether this application component has been initialized (i.e., init() is invoked.)

Method Details

getIsInitialized() method
public boolean getIsInitialized()
{return} boolean whether this application component has been initialized (i.e., init() is invoked.)

init() method
public void init()

Initializes the application component. This method is required by IApplicationComponent and is invoked by application. If you override this method, make sure to call the parent implementation so that the application component can be marked as initialized.


CBehavior

Package | system.base
Inheritance | class CBehavior » CComponent
Implements | IBehavior
Subclasses | CModelBehavior
Since | 1.0.2
Version | $Id: CBehavior.php 1678 2010-01-07 21:02:00Z qiang.xue $
CBehavior is a convenient base class for behavior classes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
enabled | boolean | whether this behavior is enabled | CBehavior
owner | CComponent | the owner component that this behavior is attached to. | CBehavior

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attach() | Attaches the behavior object to the component. | CBehavior
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detach() | Detaches the behavior object from the component. | CBehavior
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
events() | Declares events and the corresponding event handler methods. | CBehavior
getEnabled() |  | CBehavior
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOwner() |  | CBehavior
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setEnabled() |  | CBehavior

Property Details

enabled property
public boolean getEnabled()
public void setEnabled(boolean $value)

whether this behavior is enabled

owner property read-only
public CComponent getOwner()

the owner component that this behavior is attached to.

Method Details

attach() method
public void attach(CComponent $owner)
$owner CComponent the component that this behavior is to be attached to.

Attaches the behavior object to the component. The default implementation will set the owner property and attach event handlers as declared in events. Make sure you call the parent implementation if you override this method.

detach() method
public void detach(CComponent $owner)
$owner CComponent the component that this behavior is to be detached from.

Detaches the behavior object from the component. The default implementation will unset the owner property and detach event handlers declared in events. Make sure you call the parent implementation if you override this method.

events() method
public array events()
{return} array events (array keys) and the corresponding event handler methods (array values).

Declares events and the corresponding event handler methods. The events are defined by the owner component, while the handler methods by the behavior class. The handlers will be attached to the corresponding events when the behavior is attached to the owner component; and they will be detached from the events when the behavior is detached from the component.

getEnabled() method
public boolean getEnabled()
{return} boolean whether this behavior is enabled

getOwner() method
public CComponent getOwner()
{return} CComponent the owner component that this behavior is attached to.

setEnabled() method
public void setEnabled(boolean $value)
$value boolean whether this behavior is enabled


CComponent

All Packages | Methods
Package | system.base
Inheritance | class CComponent
Subclasses | CAccessRule, CAction, CActiveFinder, CApplicationComponent, CAuthAssignment, CAuthItem, CBaseActiveRelation, CBaseController, CBaseUserIdentity, CBehavior, CCacheDependency, CChainedCacheDependency, CConsoleCommand, CConsoleCommandRunner, CDataProvider, CDateFormatter, CDbColumnSchema, CDbCommand, CDbCommandBuilder, CDbDataReader, CDbExpression, CDbSchema, CDbTableSchema, CDbTransaction, CEvent, CFilter, CFormElement, CGettextFile, CGridColumn, CHttpCookie, CList, CLocale, CLogFilter, CLogRoute, CLogger, CMap, CMemCacheServerConfiguration, CModel, CModule, CNumberFormatter, CPagination, CQueue, CSort, CStack, CTheme, CUploadedFile, CUrlRule, CValidator, CWebService, CWsdlGenerator
Since | 1.0
Version | $Id: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
CComponent is the base class for all components.

CComponent implements the protocol of defining, using properties and events.

A property is defined by a getter method, and/or a setter method. Properties can be accessed in the way like accessing normal object members. Reading or writing a property will cause the invocation of the corresponding getter or setter method, e.g
$a=$component->text;     // equivalent to $a=$component->getText();
$component->text='abc';  // equivalent to $component->setText('abc');
The signatures of getter and setter methods are as follows,
// getter, defines a readable property 'text'
public function getText() { ... }
// setter, defines a writable property 'text' with $value to be set to the property
public function setText($value) { ... }

An event is defined by the presence of a method whose name starts with 'on'. The event name is the method name. When an event is raised, functions (called event handlers) attached to the event will be invoked automatically.

An event can be raised by calling raiseEvent method, upon which the attached event handlers will be invoked automatically in the order they are attached to the event. Event handlers must have the following signature,
function eventHandler($event) { ... }
where $event includes parameters associated with the event.

To attach an event handler to an event, see attachEventHandler. You can also use the following syntax:
$component->onClick=$callback;    // or $component->onClick->add($callback);
where $callback refers to a valid PHP callback. Below we show some callback examples:
'handleOnClick'                   // handleOnClick() is a global function
array($object,'handleOnClick')    // using $object->handleOnClick()
array('Page','handleOnClick')     // using Page::handleOnClick()

To raise an event, use raiseEvent. The on-method defining an event is commonly written like the following:
public function onClick($event)
{
    $this->raiseEvent('onClick',$event);
}
where $event is an instance of CEvent or its child class. One can then raise the event by calling the on-method instead of raiseEvent directly.

Both property names and event names are case-insensitive.

Starting from version 1.0.2, CComponent supports behaviors. A behavior is an instance of IBehavior which is attached to a component. The methods of the behavior can be invoked as if they belong to the component. Multiple behaviors can be attached to the same component.

To attach a behavior to a component, call attachBehavior; and to detach the behavior from the component, call detachBehavior.

A behavior can be temporarily enabled or disabled by calling enableBehavior or disableBehavior, respectively. When disabled, the behavior methods cannot be invoked via the component.

Starting from version 1.1.0, a behavior's properties (either its public member variables or its properties defined via getters and/or setters) can be accessed through the component it is attached to.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Method Details

__call() method (available since v1.0.2)
public mixed __call(string $name, array $parameters)
$name | string | the method name
$parameters | array | method parameters
{return} | mixed | the method return value

Calls the named method which is not a class method. Do not call this method. This is a PHP magic method that we override to implement the behavior feature.

__get() method
public mixed __get(string $name)
$name | string | the property name or event name
{return} | mixed | the property value, event handlers attached to the event, or the named behavior (since version 1.0.2)

Returns a property value, an event handler list or a behavior based on its name. Do not call this method. This is a PHP magic method that we override to allow using the following syntax to read a property or obtain event handlers:

$value=$component->propertyName;
$handlers=$component->eventName;

See Also

  • __set
__isset() method (available since v1.0.1)
public void __isset(string $name)
$name string the property name or the event name

Checks if a property value is null. Do not call this method. This is a PHP magic method that we override to allow using isset() to detect if a component property is set or not.

__set() method
public void __set(string $name, mixed $value)
$name | string | the property name or the event name
$value | mixed | the property value or callback

Sets value of a component property. Do not call this method. This is a PHP magic method that we override to allow using the following syntax to set a property or attach an event handler

$this->propertyName=$value;
$this->eventName=$callback;

See Also

  • __get
__unset() method (available since v1.0.1)
public void __unset(string $name)
$name string the property name or the event name

Sets a component property to be null. Do not call this method. This is a PHP magic method that we override to allow using unset() to set a component property to be null.

asa() method (available since v1.0.2)
public IBehavior asa(string $behavior)
$behavior | string | the behavior name
{return} | IBehavior | the behavior object, or null if the behavior does not exist

Returns the named behavior object. The name 'asa' stands for 'as a'.

attachBehavior() method (available since v1.0.2)
public IBehavior attachBehavior(string $name, mixed $behavior)
$name | string | the behavior's name. It should uniquely identify this behavior.
$behavior | mixed | the behavior configuration. This is passed as the first parameter to YiiBase::createComponent to create the behavior object.
{return} | IBehavior | the behavior object

Attaches a behavior to this component. This method will create the behavior object based on the given configuration. After that, the behavior object will be initialized by calling its IBehavior::attach method.

attachBehaviors() method (available since v1.0.2)
public void attachBehaviors(array $behaviors)
$behaviors array list of behaviors to be attached to the component

Attaches a list of behaviors to the component. Each behavior is indexed by its name and should be an instance of IBehavior, a string specifying the behavior class, or an array of the following structure:

array(
    'class'=>'path.to.BehaviorClass',
    'property1'=>'value1',
    'property2'=>'value2',
)

attachEventHandler() method
public void attachEventHandler(string $name, callback $handler)
$name | string | the event name
$handler | callback | the event handler

Attaches an event handler to an event.

An event handler must be a valid PHP callback, i.e., a string referring to a global function name, or an array containing two elements with the first element being an object and the second element a method name of the object.

An event handler must be defined with the following signature,

function handlerName($event) {}
where $event includes parameters associated with the event.

This is a convenient method of attaching a handler to an event. It is equivalent to the following code:
$component->getEventHandlers($eventName)->add($eventHandler);

Using getEventHandlers, one can also specify the excution order of multiple handlers attaching to the same event. For example:
$component->getEventHandlers($eventName)->insertAt(0,$eventHandler);
makes the handler to be invoked first.

See Also

  • detachEventHandler
canGetProperty() method
public boolean canGetProperty(string $name)
$name | string | the property name
{return} | boolean | whether the property can be read

Determines whether a property can be read. A property can be read if the class has a getter method for the property name. Note, property name is case-insensitive.

See Also

  • canSetProperty
canSetProperty() method
public boolean canSetProperty(string $name)
$name | string | the property name
{return} | boolean | whether the property can be written

Determines whether a property can be set. A property can be written if the class has a setter method for the property name. Note, property name is case-insensitive.

See Also

  • canGetProperty
detachBehavior() method (available since v1.0.2)
public IBehavior detachBehavior(string $name)
$name | string | the behavior's name. It uniquely identifies the behavior.
{return} | IBehavior | the detached behavior. Null if the behavior does not exist.

Detaches a behavior from the component. The behavior's IBehavior::detach method will be invoked.

detachBehaviors() method (available since v1.0.2)
public void detachBehaviors()

Detaches all behaviors from the component.

detachEventHandler() method
public boolean detachEventHandler(string $name, callback $handler)
$name | string | event name
$handler | callback | the event handler to be removed
{return} | boolean | if the detachment process is successful

Detaches an existing event handler. This method is the opposite of attachEventHandler.

See Also

  • attachEventHandler
disableBehavior() method (available since v1.0.2)
public void disableBehavior(string $name)
$name string the behavior's name. It uniquely identifies the behavior.

Disables an attached behavior. A behavior is only effective when it is enabled.

disableBehaviors() method (available since v1.0.2)
public void disableBehaviors()

Disables all behaviors attached to this component.

enableBehavior() method (available since v1.0.2)
public void enableBehavior(string $name)
$name string the behavior's name. It uniquely identifies the behavior.

Enables an attached behavior. A behavior is only effective when it is enabled. A behavior is enabled when first attached.

enableBehaviors() method (available since v1.0.2)
public void enableBehaviors()

Enables all behaviors attached to this component.

evaluateExpression() method (available since v1.1.0)
public mixed evaluateExpression(array $_expression_, $_data_=array ( ))
$_expression_ | array | additional parameters to be passed to the above expression/callback.
$_data_ |  |
{return} | mixed | the expression result

Evaluates a PHP expression or callback under the context of this component.

Valid PHP callback can be class method name in the form of array(ClassName/Object, MethodName), or anonymous function (only available in PHP 5.3.0 or above).

If a PHP callback is used, the corresponding function/method signature should be

function foo($param1, $param2, ..., $component) { ... }
where the array elements in the second parameter to this method will be passed to the callback as $param1, $param2, ...; and the last parameter will be the component itself.

If a PHP expression is used, the second parameter will be "extracted" into PHP variables that can be directly accessed in the expression. See PHP extract for more details. In the expression, the component object can be accessed using $this.

getEventHandlers() method
public CList getEventHandlers(string $name)
$name | string | the event name
{return} | CList | list of attached event handlers for the event

Returns the list of attached event handlers for an event.

hasEvent() method
public boolean hasEvent(string $name)
$name | string | the event name
{return} | boolean | whether an event is defined

Determines whether an event is defined. An event is defined if the class has a method named like 'onXXX'. Note, event name is case-insensitive.

hasEventHandler() method
public boolean hasEventHandler(string $name)
$name | string | the event name
{return} | boolean | whether an event has been attached one or several handlers

Checks whether the named event has attached handlers.

hasProperty() method
public boolean hasProperty(string $name)
$name | string | the property name
{return} | boolean | whether the property is defined

Determines whether a property is defined. A property is defined if there is a getter or setter method defined in the class. Note, property names are case-insensitive.

See Also

  • canGetProperty
  • canSetProperty
raiseEvent() method
public void raiseEvent(string $name, CEvent $event)
$name | string | the event name
$event | CEvent | the event parameter

Raises an event. This method represents the happening of an event. It invokes all attached handlers for the event.


CEnumerable

All Packages
Package | system.base
Inheritance | class CEnumerable
Since | 1.0
Version | $Id: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
CEnumerable is the base class for all enumerable types.

To define an enumerable type, extend CEnumberable and define string constants. Each constant represents an enumerable value. The constant name must be the same as the constant value. For example,
class TextAlign extends CEnumerable
{
    const Left='Left';
    const Right='Right';
}
Then, one can use the enumerable values such as TextAlign::Left and TextAlign::Right.


CErrorEvent

Package | system.base
Inheritance | class CErrorEvent » CEvent » CComponent
Since | 1.0
Version | $Id: CErrorEvent.php 1678 2010-01-07 21:02:00Z qiang.xue $
CErrorEvent represents the parameter for the onError event.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
code | string | error code | CErrorEvent
file | string | error message | CErrorEvent
handled | boolean | whether the event is handled. | CEvent
line | string | error file | CErrorEvent
message | string | error message | CErrorEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CErrorEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

code property
public string $code;

error code

file property
public string $file;

error message

line property
public string $line;

error file

message property
public string $message;

error message

Method Details

__construct() method
public void __construct(mixed $sender, string $code, string $message, string $file, integer $line)
$sender | mixed | sender of the event
$code | string | error code
$message | string | error message
$file | string | error file
$line | integer | error line

Constructor.


CErrorHandler

Package | system.base
Inheritance | class CErrorHandler » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CErrorHandler.php 1789 2010-02-02 18:38:56Z qiang.xue $
CErrorHandler handles uncaught PHP errors and exceptions.

It displays these errors using appropriate views based on the nature of the error and the mode the application runs at. It also chooses the most preferred language for displaying the error.

CErrorHandler uses two sets of views:
  • development views, named as exception.php;
  • production views, named as error<StatusCode>.php;
where <StatusCode> stands for the HTTP error code (e.g. error500.php). Localized views are named similarly but located under a subdirectory whose name is the language code (e.g. zh_cn/error500.php).

Development views are displayed when the application is in debug mode (i.e. YII_DEBUG is defined as true). Detailed error information with source code are displayed in these views. Production views are meant to be shown to end-users and are used when the application is in production mode. For security reasons, they only display the error message without any sensitive information.

CErrorHandler looks for the view templates from the following locations in order:
  1. themes/ThemeName/views/system: when a theme is active.
  2. protected/views/system
  3. framework/views
If the view is not found in a directory, it will be looked for in the next directory.

The property maxSourceLines can be changed to specify the number of source code lines to be displayed in development views.

CErrorHandler is a core application component that can be accessed via CApplication::getErrorHandler().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
adminInfo | string | the application administrator information (could be a name or email link). | CErrorHandler
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
discardOutput | boolean | whether to discard any existing page output before error display. | CErrorHandler
error | array | Returns the details about the error that is currently being handled. | CErrorHandler
errorAction | string | the route (e. | CErrorHandler
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
maxSourceLines | integer | maximum number source code lines to be displayed. | CErrorHandler

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
versionInfo | string | server version information. | CErrorHandler

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getError() | Returns the details about the error that is currently being handled. | CErrorHandler
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
handle() | Handles the exception/error event. | CErrorHandler
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
getExactTrace() |  | CErrorHandler
getSourceLines() | Returns the source lines around the error line. | CErrorHandler
getVersionInfo() |  | CErrorHandler
getViewFile() | Determines which view file should be used. | CErrorHandler
getViewFileInternal() | Looks for the view under the specified directory. | CErrorHandler
handleError() | Handles the PHP error. | CErrorHandler
handleException() | Handles the exception. | CErrorHandler
render() | Renders the view. | CErrorHandler

Property Details

adminInfo property
public string $adminInfo;

the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.

discardOutput property
public boolean $discardOutput;

whether to discard any existing page output before error display. Defaults to true.

error property read-only (available since v1.0.6)
public array getError()

Returns the details about the error that is currently being handled. The error is returned in terms of an array, with the following information:

  • code - the HTTP status code (e.g. 403, 500)
  • type - the error type (e.g. 'CHttpException', 'PHP Error')
  • message - the error message
  • file - the name of the PHP script file where the error occurs
  • line - the line number of the code where the error occurs
  • trace - the call stack of the error
  • source - the context source code where the error occurs

errorAction property (available since v1.0.6)
public string $errorAction;

the route (e.g. 'site/error') to the controller action that will be used to display external errors. Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error. This property defaults to null, meaning CErrorHandler will handle the error display.

maxSourceLines property
public integer $maxSourceLines;

maximum number source code lines to be displayed. Defaults to 25.

versionInfo property read-only
protected string getVersionInfo()

server version information. If the application is in production mode, nothing is returned.

Method Details

getError() method (available since v1.0.6)
public array getError()
{return} array the error details. Null if there is no error.

Returns the details about the error that is currently being handled. The error is returned in terms of an array, with the following information:

  • code - the HTTP status code (e.g. 403, 500)
  • type - the error type (e.g. 'CHttpException', 'PHP Error')
  • message - the error message
  • file - the name of the PHP script file where the error occurs
  • line - the line number of the code where the error occurs
  • trace - the call stack of the error
  • source - the context source code where the error occurs

getExactTrace() method
protected array getExactTrace(Exception $exception)
$exception | Exception | the uncaught exception
{return} | array | the exact trace where the problem occurs

getSourceLines() method
protected array getSourceLines(string $file, integer $line)
$file | string | source file path
$line | integer | the error line number
{return} | array | source lines around the error line, indxed by line numbers

Returns the source lines around the error line. At most maxSourceLines lines will be returned.

getVersionInfo() method
protected string getVersionInfo()
{return} string server version information. If the application is in production mode, nothing is returned.

getViewFile() method
protected string getViewFile(string $view, integer $code)
$view | string | view name (either 'exception' or 'error')
$code | integer | HTTP status code
{return} | string | view file path

Determines which view file should be used.

getViewFileInternal() method
protected string getViewFileInternal(string $viewPath, string $view, integer $code, string $srcLanguage=NULL)
$viewPath | string | the directory containing the views
$view | string | view name (either 'exception' or 'error')
$code | integer | HTTP status code
$srcLanguage | string | the language that the view file is in
{return} | string | view file path

Looks for the view under the specified directory.

handle() method
public void handle(CEvent $event)
$event CEvent the event containing the exception/error information

Handles the exception/error event. This method is invoked by the application whenever it captures an exception or PHP error.

handleError() method
protected void handleError(CErrorEvent $event)
$event CErrorEvent the PHP error event

Handles the PHP error.

handleException() method
protected void handleException(Exception $exception)
$exception Exception the exception captured

Handles the exception.

render() method
protected void render(string $view, array $data)
$view | string | the view name (file name without extension). See getViewFile for how a view file is located given its name.
$data | array | data to be passed to the view

Renders the view.


CEvent

Package | system.base
Inheritance | class CEvent » CComponent
Subclasses | CErrorEvent, CExceptionEvent, CMissingTranslationEvent, CModelEvent, COutputEvent
Since | 1.0
Version | $Id: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
CEvent is the base class for all event classes.

It encapsulates the parameters associated with an event. The sender property describes who raises the event. And the handled property indicates if the event is handled. If an event handler sets handled to true, those handlers that are not invoked yet will not be invoked anymore.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
handled | boolean | whether the event is handled. | CEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

handled property
public boolean $handled;

whether the event is handled. Defaults to false. When a handler sets this true, the rest uninvoked handlers will not be invoked anymore.

sender property
public object $sender;

the sender of this event

Method Details

__construct() method
public void __construct(mixed $sender=NULL)
$sender mixed sender of the event

Constructor.


CException

Package | system.base
Inheritance | class CException » Exception
Subclasses | CDbException, CHttpException
Since | 1.0
Version | $Id: CException.php 1678 2010-01-07 21:02:00Z qiang.xue $
CException represents a generic exception for all purposes.

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
code |  |  | Exception
file |  |  | Exception
line |  |  | Exception
message |  |  | Exception

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() |  | Exception
__toString() |  | Exception
getCode() |  | Exception
getFile() |  | Exception
getLine() |  | Exception
getMessage() |  | Exception
getTrace() |  | Exception
getTraceAsString() |  | Exception


CExceptionEvent

Package | system.base
Inheritance | class CExceptionEvent » CEvent » CComponent
Since | 1.0
Version | $Id: CExceptionEvent.php 1678 2010-01-07 21:02:00Z qiang.xue $
CExceptionEvent represents the parameter for the onException event.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
exception | CException | the exception that this event is about. | CExceptionEvent
handled | boolean | whether the event is handled. | CEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CExceptionEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

exception property
public CException $exception;

the exception that this event is about.

Method Details

__construct() method
public void __construct(mixed $sender, CException $exception)
$sender | mixed | sender of the event
$exception | CException | the exception

Constructor.


CHttpException

Package | system.base
Inheritance | class CHttpException » CException » Exception
Since | 1.0
Version | $Id: CHttpException.php 1678 2010-01-07 21:02:00Z qiang.xue $
CHttpException represents an exception caused by invalid operations of end-users.

The HTTP error code can be obtained via statusCode. Error handlers may use this status code to decide how to format the error page.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
statusCode | integer | HTTP status code, such as 403, 404, 500, etc. | CHttpException

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
code |  |  | Exception
file |  |  | Exception
line |  |  | Exception
message |  |  | Exception

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CHttpException
__toString() |  | Exception
getCode() |  | Exception
getFile() |  | Exception
getLine() |  | Exception
getMessage() |  | Exception
getTrace() |  | Exception
getTraceAsString() |  | Exception

Property Details

statusCode property
public integer $statusCode;

HTTP status code, such as 403, 404, 500, etc.

Method Details

__construct() method
public void __construct(integer $status, string $message=NULL, integer $code=0)
$status | integer | HTTP status code, such as 404, 500, etc.
$message | string | error message
$code | integer | error code

Constructor.


CModel

All Packages | Properties | Methods | Events
Package | system.base
Inheritance | abstract class CModel » CComponent
Implements | IteratorAggregate, Traversable, ArrayAccess
Subclasses | CActiveRecord, CFormModel
Since | 1.0
Version | $Id: CModel.php 1859 2010-03-06 04:21:12Z qiang.xue $
CModel is the base class providing the common features needed by data model objects.

CModel defines the basic framework for data models that need to be validated.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | Returns all attribute values. | CModel
errors | array | Returns the errors for all attribute or a single attribute. | CModel
iterator | CMapIterator | Returns an iterator for traversing the attributes in the model. | CModel
safeAttributeNames | array | Returns the attribute names that are safe to be massively assigned. | CModel
scenario | string | Returns the scenario that this model is used in. | CModel
validators | array | Returns the validators applicable to the current scenario. | CModel

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addError() | Adds a new error to the specified attribute. | CModel
addErrors() | Adds a list of errors. | CModel
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
attributeLabels() | Returns the attribute labels. | CModel
attributeNames() | Returns the list of attribute names of the model. | CModel
behaviors() | Returns a list of behaviors that this model should behave as. | CModel
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearErrors() | Removes errors for all attributes or a single attribute. | CModel
createValidators() | Creates validator objects based on the specification in rules. | CModel
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
generateAttributeLabel() | Generates a user friendly attribute label. | CModel
getAttributeLabel() | Returns the text label for the specified attribute. | CModel
getAttributes() | Returns all attribute values. | CModel
getError() | Returns the first error of the specified attribute. | CModel
getErrors() | Returns the errors for all attribute or a single attribute. | CModel
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the attributes in the model. | CModel
getSafeAttributeNames() | Returns the attribute names that are safe to be massively assigned. | CModel
getScenario() | Returns the scenario that this model is used in. | CModel
getValidators() | Returns the validators applicable to the current scenario. | CModel
hasErrors() | Returns a value indicating whether there is any validation error. | CModel
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
isAttributeRequired() | Returns a value indicating whether the attribute is required. | CModel
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | CModel
offsetExists() | Returns whether there is an element at the specified offset. | CModel
offsetGet() | Returns the element at the specified offset. | CModel
offsetSet() | Sets the element at the specified offset. | CModel
offsetUnset() | Unsets the element at the specified offset. | CModel
onAfterValidate() | This event is raised after the validation is performed. | CModel
onBeforeValidate() | This event is raised before the validation is performed. | CModel
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | CModel
raiseEvent() | Raises an event. | CComponent
rules() | Returns the validation rules for attributes. | CModel
setAttributes() | Sets the attribute values in a massive way. | CModel
setScenario() |  | CModel
validate() | Performs the validation. | CModel

Protected Methods

Hide inherited methods

Method | Description | Defined By
afterValidate() | This method is invoked after validation ends. | CModel
beforeValidate() | This method is invoked before validation starts. | CModel

Events

Hide inherited events

Event | Description | Defined By
onBeforeValidate | This event is raised before the validation is performed. | CModel
onAfterValidate | This event is raised after the validation is performed. | CModel
onUnsafeAttribute | This method is invoked when an unsafe attribute is being massively assigned. | CModel

Property Details

attributes property
public array getAttributes(array $names=NULL)
public void setAttributes(array $values, boolean $safeOnly=true)

Returns all attribute values.

errors property read-only
public array getErrors(string $attribute=NULL)

Returns the errors for all attribute or a single attribute.

iterator property read-only
public CMapIterator getIterator()

Returns an iterator for traversing the attributes in the model. This method is required by the interface IteratorAggregate.

safeAttributeNames property read-only (available since v1.0.2)
public array getSafeAttributeNames()

Returns the attribute names that are safe to be massively assigned. A safe attribute is one that is associated with a validation rule in the current scenario.

scenario property (available since v1.0.4)
public string getScenario()
public void setScenario(string $value)

Returns the scenario that this model is used in.

Scenario affects how validation is performed and which attributes can be massively assigned.

A validation rule will be performed when calling validate() if its 'on' option is not set or contains the current scenario value.

And an attribute can be massively assigned if it is associated with a validation rule for the current scenario. Note that an exception is the unsafe validator which marks the associated attributes as unsafe and not allowed to be massively assigned.

validators property read-only (available since v1.0.1)
public array getValidators(string $attribute=NULL)

Returns the validators applicable to the current scenario.

Method Details

addError() method
public void addError(string $attribute, string $error)
$attribute | string | attribute name
$error | string | new error message

Adds a new error to the specified attribute.

addErrors() method (available since v1.0.5)
public void addErrors(array $errors)
$errors array a list of errors. The array keys must be attribute names. The array values should be error messages. If an attribute has multiple errors, these errors must be given in terms of an array. You may use the result of getErrors as the value for this parameter.

Adds a list of errors.

afterValidate() method
protected void afterValidate()

This method is invoked after validation ends. The default implementation calls onAfterValidate to raise an event. You may override this method to do postprocessing after validation. Make sure the parent implementation is invoked so that the event can be raised.

attributeLabels() method
public array attributeLabels()
{return} array attribute labels (name=>label)

Returns the attribute labels. Attribute labels are mainly used in error messages of validation. By default an attribute label is generated using generateAttributeLabel. This method allows you to explicitly specify attribute labels.

Note, in order to inherit labels defined in the parent class, a child class needs to merge the parent labels with child labels using functions like array_merge().

See Also

  • generateAttributeLabel
attributeNames() method (available since v1.0.1)
abstract public array attributeNames()
{return} array list of attribute names.

Returns the list of attribute names of the model.

beforeValidate() method
protected boolean beforeValidate()
{return} boolean whether validation should be executed. Defaults to true.

This method is invoked before validation starts. The default implementation calls onBeforeValidate to raise an event. You may override this method to do preliminary checks before validation. Make sure the parent implementation is invoked so that the event can be raised.

behaviors() method (available since v1.0.2)
public array behaviors()
{return} array the behavior configurations (behavior name=>behavior configuration)

Returns a list of behaviors that this model should behave as. The return value should be an array of behavior configurations indexed by behavior names. Each behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName'=>array(
    'class'=>'path.to.BehaviorClass',
    'property1'=>'value1',
    'property2'=>'value2',
)

Note, the behavior classes must implement IBehavior or extend from CBehavior. Behaviors declared in this method will be attached to the model when it is instantiated.

For more details about behaviors, see CComponent.

clearErrors() method
public void clearErrors(string $attribute=NULL)
$attribute string attribute name. Use null to remove errors for all attribute.

Removes errors for all attributes or a single attribute.

createValidators() method
public array createValidators()
{return} array validators built based on rules().

Creates validator objects based on the specification in rules. This method is mainly used internally.

generateAttributeLabel() method
public string generateAttributeLabel(string $name)
$name | string | the column name
{return} | string | the attribute label

Generates a user friendly attribute label. This is done by replacing underscores or dashes with blanks and changing the first letter of each word to upper case. For example, 'department_name' or 'DepartmentName' becomes 'Department Name'.

getAttributeLabel() method
public string getAttributeLabel(string $attribute)
$attribute | string | the attribute name
{return} | string | the attribute label

Returns the text label for the specified attribute.

See Also

  • generateAttributeLabel
  • attributeLabels
getAttributes() method
public array getAttributes(array $names=NULL)
$names | array | list of attributes whose value needs to be returned. Defaults to null, meaning all attributes as listed in attributeNames will be returned. If it is an array, only the attributes in the array will be returned.
{return} | array | attribute values (name=>value).

Returns all attribute values.

getError() method (available since v1.0.2)
public string getError(string $attribute)
$attribute | string | attribute name.
{return} | string | the error message. Null is returned if no error.

Returns the first error of the specified attribute.

getErrors() method
public array getErrors(string $attribute=NULL)
$attribute | string | attribute name. Use null to retrieve errors for all attributes.
{return} | array | errors for all attributes or the specified attribute. Empty array is returned if no error.

Returns the errors for all attribute or a single attribute.

getIterator() method
public CMapIterator getIterator()
{return} CMapIterator an iterator for traversing the items in the list.

Returns an iterator for traversing the attributes in the model. This method is required by the interface IteratorAggregate.

getSafeAttributeNames() method (available since v1.0.2)
public array getSafeAttributeNames()
{return} array safe attribute names

Returns the attribute names that are safe to be massively assigned. A safe attribute is one that is associated with a validation rule in the current scenario.

getScenario() method (available since v1.0.4)
public string getScenario()
{return} string the scenario that this model is in.

Returns the scenario that this model is used in.

Scenario affects how validation is performed and which attributes can be massively assigned.

A validation rule will be performed when calling validate() if its 'on' option is not set or contains the current scenario value.

And an attribute can be massively assigned if it is associated with a validation rule for the current scenario. Note that an exception is the unsafe validator which marks the associated attributes as unsafe and not allowed to be massively assigned.

getValidators() method (available since v1.0.1)
public array getValidators(string $attribute=NULL)
$attribute | string | the name of the attribute whose validators should be returned. If this is null, the validators for ALL attributes in the model will be returned.
{return} | array | the validators applicable to the current scenario.

Returns the validators applicable to the current scenario.

hasErrors() method
public boolean hasErrors(string $attribute=NULL)
$attribute | string | attribute name. Use null to check all attributes.
{return} | boolean | whether there is any error.

Returns a value indicating whether there is any validation error.

isAttributeRequired() method (available since v1.0.2)
public boolean isAttributeRequired(string $attribute)
$attribute | string | attribute name
{return} | boolean | whether the attribute is required

Returns a value indicating whether the attribute is required. This is determined by checking if the attribute is associated with a CRequiredValidator validation rule in the current scenario.

isAttributeSafe() method (available since v1.1)
public boolean isAttributeSafe(string $attribute)
$attribute | string | attribute name
{return} | boolean | whether the attribute is safe for massive assignments

Returns a value indicating whether the attribute is safe for massive assignments.

offsetExists() method (available since v1.0.2)
public boolean offsetExists(mixed $offset)
$offset | mixed | the offset to check on
{return} | boolean |

Returns whether there is an element at the specified offset. This method is required by the interface ArrayAccess.

offsetGet() method (available since v1.0.2)
public mixed offsetGet(integer $offset)
$offset | integer | the offset to retrieve element.
{return} | mixed | the element at the offset, null if no element is found at the offset

Returns the element at the specified offset. This method is required by the interface ArrayAccess.

offsetSet() method (available since v1.0.2)
public void offsetSet(integer $offset, mixed $item)
$offset | integer | the offset to set element
$item | mixed | the element value

Sets the element at the specified offset. This method is required by the interface ArrayAccess.

offsetUnset() method (available since v1.0.2)
public void offsetUnset(mixed $offset)
$offset mixed the offset to unset element

Unsets the element at the specified offset. This method is required by the interface ArrayAccess.

onAfterValidate() method (available since v1.0.2)
public void onAfterValidate(CEvent $event)
$event CEvent the event parameter

This event is raised after the validation is performed.

onBeforeValidate() method (available since v1.0.2)
public void onBeforeValidate(CModelEvent $event)
$event CModelEvent the event parameter

This event is raised before the validation is performed.

onUnsafeAttribute() method (available since v1.1.1)
public void onUnsafeAttribute(string $name, mixed $value)
$name | string | the unsafe attribute name
$value | mixed | the attribute value

This method is invoked when an unsafe attribute is being massively assigned. The default implementation will log a warning message if YII_DEBUG is on. It does nothing otherwise.

rules() method
public array rules()
{return} array validation rules to be applied when validate() is called.

Returns the validation rules for attributes.

This method should be overridden to declare validation rules. Each rule is an array with the following structure:

array('attribute list', 'validator name', 'on'=>'scenario name', ...validation parameters...)
where
  • attribute list: specifies the attributes (separated by commas) to be validated;
  • validator name: specifies the validator to be used. It can be the name of a model class method, the name of a built-in validator, or a validator class (or its path alias). A validation method must have the following signature:
    // $params refers to validation parameters given in the rule
function validatorName($attribute,$params)
    A built-in validator refers to one of the validators declared in CValidator::builtInValidators. And a validator class is a class extending CValidator.
  • on: this specifies the scenarios when the validation rule should be performed. Separate different scenarios with commas. If this option is not set, the rule will be applied in any scenario. Please see scenario for more details about this option.
  • additional parameters are used to initialize the corresponding validator properties. Please refer to individal validator class API for possible properties.

The following are some examples:
array(
    array('username', 'required'),
    array('username', 'length', 'min'=>3, 'max'=>12),
    array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
    array('password', 'authenticate', 'on'=>'login'),
);

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions like array_merge().

See Also

  • scenario
setAttributes() method
public void setAttributes(array $values, boolean $safeOnly=true)
$values | array | attribute values (name=>value) to be set.
$safeOnly | boolean | whether the assignments should only be done to the safe attributes. A safe attribute is one that is associated with a validation rule in the current scenario.

Sets the attribute values in a massive way.

See Also

  • getSafeAttributeNames
  • attributeNames
setScenario() method (available since v1.0.4)
public void setScenario(string $value)
$value string the scenario that this model is in.

See Also

  • getScenario
validate() method
public boolean validate(array $attributes=NULL)
$attributes | array | list of attributes that should be validated. Defaults to null, meaning any attribute listed in the applicable validation rules should be validated. If this parameter is given as a list of attributes, only the listed attributes will be validated.
{return} | boolean | whether the validation is successful without any error.

Performs the validation.

This method executes the validation rules as declared in rules. Only the rules applicable to the current scenario will be executed. A rule is considered applicable to a scenario if its 'on' option is not set or contains the scenario.

Errors found during the validation can be retrieved via getErrors.

See Also

  • beforeValidate
  • afterValidate


CModelBehavior

Package | system.base
Inheritance | class CModelBehavior » CBehavior » CComponent
Implements | IBehavior
Subclasses | CActiveRecordBehavior
Since | 1.0.2
Version | $Id: CModelBehavior.php 1678 2010-01-07 21:02:00Z qiang.xue $
CModelBehavior is a base class for behaviors that are attached to a model component. The model should extend from CModel or its child classes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
enabled | boolean | whether this behavior is enabled | CBehavior
owner | CComponent | the owner component that this behavior is attached to. | CBehavior

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
afterValidate() | Responds to CModel::onAfterValidate event. | CModelBehavior
asa() | Returns the named behavior object. | CComponent
attach() | Attaches the behavior object to the component. | CBehavior
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beforeValidate() | Responds to CModel::onBeforeValidate event. | CModelBehavior
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detach() | Detaches the behavior object from the component. | CBehavior
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
events() | Declares events and the corresponding event handler methods. | CModelBehavior
getEnabled() |  | CBehavior
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOwner() |  | CBehavior
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setEnabled() |  | CBehavior

Method Details

afterValidate() method
public void afterValidate(CEvent $event)
$event CEvent event parameter

Responds to CModel::onAfterValidate event. Overrides this method if you want to handle the corresponding event of the owner.

beforeValidate() method
public void beforeValidate(CModelEvent $event)
$event CModelEvent event parameter

Responds to CModel::onBeforeValidate event. Overrides this method if you want to handle the corresponding event of the owner. You may set CModelEvent::isValid to be false to quit the validation process.

events() method
public array events()
{return} array events (array keys) and the corresponding event handler methods (array values).

Declares events and the corresponding event handler methods. The default implementation returns 'onBeforeValidate' and 'onAfterValidate' events and handlers. If you override this method, make sure you merge the parent result to the return value.

See Also

  • CBehavior::events


CModelEvent

Package | system.base
Inheritance | class CModelEvent » CEvent » CComponent
Since | 1.0
Version | $Id: CModelEvent.php 1678 2010-01-07 21:02:00Z qiang.xue $
CModelEvent class.

CModelEvent represents the event parameters needed by events raised by a model.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
handled | boolean | whether the event is handled. | CEvent
isValid | boolean | whether the model is in valid status and should continue its normal method execution cycles. | CModelEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

isValid property
public boolean $isValid;

whether the model is in valid status and should continue its normal method execution cycles. Defaults to true. For example, when this event is raised in a CFormModel object when executing CModel::beforeValidate, if this property is false by the event handler, the CModel::validate method will quit after handling this event. If true, the normal execution cycles will continue, including performing the real validations and calling CModel::afterValidate.


CModule

Package | system.base
Inheritance | abstract class CModule » CComponent
Subclasses | CApplication, CWebModule
Since | 1.0.4
Version | $Id: CModule.php 1815 2010-02-18 22:01:55Z qiang.xue $
CModule is the base class for module and application classes.

CModule mainly manages application components and sub-modules.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the root directory of the module. | CModule
behaviors | array | the behaviors that should be attached to the module. | CModule
components | array | the currently loaded components (indexed by their IDs) | CModule
id | string | the module ID. | CModule
modulePath | string | the directory that contains the application modules. | CModule
modules | array | the configuration of the currently installed modules (module ID => configuration) | CModule
params | CAttributeCollection | the list of user-defined parameters | CModule
parentModule | CModule | the parent module. | CModule
preload | array | the IDs of the application components that should be preloaded. | CModule

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CModule
__get() | Getter magic method. | CModule
__isset() | Checks if a property value is null. | CModule
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures the module with the specified configuration. | CModule
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBasePath() |  | CModule
getComponent() | Retrieves the named application component. | CModule
getComponents() |  | CModule
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CModule
getModule() | Retrieves the named application module. | CModule
getModulePath() |  | CModule
getModules() |  | CModule
getParams() |  | CModule
getParentModule() |  | CModule
hasComponent() |  | CModule
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setAliases() | Defines the root aliases. | CModule
setBasePath() | Sets the root directory of the module. | CModule
setComponent() | Puts a component under the management of the module. | CModule
setComponents() | Sets the application components. | CModule
setId() |  | CModule
setImport() | Sets the aliases that are used in the module. | CModule
setModulePath() |  | CModule
setModules() | Configures the sub-modules of this module. | CModule
setParams() |  | CModule

Protected Methods

Hide inherited methods

Method | Description | Defined By
init() | Initializes the module. | CModule
preinit() | Preinitializes the module. | CModule
preloadComponents() | Loads static application components. | CModule

Property Details

basePath property
public string getBasePath()
public void setBasePath(string $path)

the root directory of the module. Defaults to the directory containing the module class.

behaviors property
public array $behaviors;

the behaviors that should be attached to the module. The behaviors will be attached to the module when init is called. Please refer to CModel::behaviors on how to specify the value of this property.

components property
public array getComponents()
public void setComponents(array $components)

the currently loaded components (indexed by their IDs)

id property
public string getId()
public void setId(string $id)

the module ID.

modulePath property
public string getModulePath()
public void setModulePath(string $value)

the directory that contains the application modules. Defaults to the 'modules' subdirectory of basePath.

modules property
public array getModules()
public void setModules(array $modules)

the configuration of the currently installed modules (module ID => configuration)

params property
public CAttributeCollection getParams()
public void setParams(array $value)

the list of user-defined parameters

parentModule property read-only
public CModule getParentModule()

the parent module. Null if this module does not have a parent.

preload property
public array $preload;

the IDs of the application components that should be preloaded.

Method Details

__construct() method
public void __construct(string $id, CModule $parent, mixed $config=NULL)
$id | string | the ID of this module
$parent | CModule | the parent module (if any)
$config | mixed | the module configuration. It can be either an array or the path of a PHP file returning the configuration array.

Constructor.

__get() method
public mixed __get(string $name)
$name | string | application component or property name
{return} | mixed | the named property value

Getter magic method. This method is overridden to support accessing application components like reading module properties.

__isset() method
public boolean __isset(string $name)
$name | string | the property name or the event name
{return} | boolean | whether the property value is null

Checks if a property value is null. This method overrides the parent implementation by checking if the named application component is loaded.

configure() method
public void configure(array $config)
$config array the configuration array

Configures the module with the specified configuration.

getBasePath() method
public string getBasePath()
{return} string the root directory of the module. Defaults to the directory containing the module class.

getComponent() method
public IApplicationComponent getComponent(string $id, boolean $createIfNull=true)
$id | string | application component ID (case-sensitive)
$createIfNull | boolean | whether to create the component if it doesn't exist yet. This parameter has been available since version 1.0.6.
{return} | IApplicationComponent | the application component instance, null if the application component is disabled or does not exist.

Retrieves the named application component.

See Also

  • hasComponent
getComponents() method
public array getComponents()
{return} array the currently loaded components (indexed by their IDs)

getId() method
public string getId()
{return} string the module ID.

getModule() method
public CModule getModule(string $id)
$id | string | application module ID (case-sensitive)
{return} | CModule | the module instance, null if the module is disabled or does not exist.

Retrieves the named application module. The module has to be declared in modules. A new instance will be created when calling this method with the given ID for the first time.

getModulePath() method
public string getModulePath()
{return} string the directory that contains the application modules. Defaults to the 'modules' subdirectory of basePath.

getModules() method
public array getModules()
{return} array the configuration of the currently installed modules (module ID => configuration)

getParams() method
public CAttributeCollection getParams()
{return} CAttributeCollection the list of user-defined parameters

getParentModule() method
public CModule getParentModule()
{return} CModule the parent module. Null if this module does not have a parent.

hasComponent() method
public boolean hasComponent(string $id)
$id | string | application component ID
{return} | boolean | whether the named application component exists (including both loaded and disabled.)

init() method
protected void init()

Initializes the module. This method is called at the end of the module constructor. Note that at this moment, the module has been configured, the behaviors have been attached and the application components have been registered.

See Also

  • preinit
preinit() method
protected void preinit()

Preinitializes the module. This method is called at the beginning of the module constructor. You may override this method to do some customized preinitialization work. Note that at this moment, the module is not configured yet.

See Also

  • init
preloadComponents() method
protected void preloadComponents()

Loads static application components.

setAliases() method (available since v1.0.5)
public void setAliases(array $mappings)
$mappings array list of aliases to be defined. The array keys are root aliases, while the array values are paths or aliases corresponding to the root aliases. For example,
array(
   'models'=>'application.models',              // an existing alias
   'extensions'=>'application.extensions',      // an existing alias
   'backend'=>dirname(__FILE__).'/../backend',  // a directory
)

Defines the root aliases.

setBasePath() method
public void setBasePath(string $path)
$path string the root directory of the module.

Sets the root directory of the module. This method can only be invoked at the beginning of the constructor.

setComponent() method
public void setComponent(string $id, IApplicationComponent $component)
$id | string | component ID
$component | IApplicationComponent | the component

Puts a component under the management of the module. The component will be initialized (by calling its init() method if it has not done so.

setComponents() method
public void setComponents(array $components)
$components array application components(id=>component configuration or instances)

Sets the application components.

When a configuration is used to specify a component, it should consist of the component's initial property values (name-value pairs). Additionally, a component can be enabled (default) or disabled by specifying the 'enabled' value in the configuration.

If a configuration is specified with an ID that is the same as an existing component or configuration, the existing one will be replaced silently.

The following is the configuration for two components:

array(
    'db'=>array(
        'class'=>'CDbConnection',
        'connectionString'=>'sqlite:path/to/file.db',
    ),
    'cache'=>array(
        'class'=>'CDbCache',
        'connectionID'=>'db',
        'enabled'=>!YII_DEBUG,  // enable caching in non-debug mode
    ),
)

setId() method
public void setId(string $id)
$id string the module ID

setImport() method
public void setImport(array $aliases)
$aliases array list of aliases to be imported

Sets the aliases that are used in the module.

setModulePath() method
public void setModulePath(string $value)
$value string the directory that contains the application modules.

setModules() method
public void setModules(array $modules)
$modules array module configurations.

Configures the sub-modules of this module.

Call this method to declare sub-modules and configure them with their initial property values. The parameter should be an array of module configurations. Each array element represents a single module, which can be either a string representing the module ID or an ID-configuration pair representing a module with the specified ID and the initial property values.

For example, the following array declares two modules:

array(
    'admin',                // a single module ID
    'payment'=>array(       // ID-configuration pair
        'server'=>'paymentserver.com',
    ),
)

By default, the module class is determined using the expression ucfirst($moduleID).'Module'. And the class file is located under modules/$moduleID. You may override this default by explicitly specifying the 'class' option in the configuration.

You may also enable or disable a module by specifying the 'enabled' option in the configuration.

setParams() method
public void setParams(array $value)
$value array user-defined parameters. This should be in name-value pairs.


CSecurityManager

Package | system.base
Inheritance | class CSecurityManager » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CSecurityManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSecurityManager provides private keys, hashing and encryption functions.

CSecurityManager is used by Yii components and applications for security-related purpose. For example, it is used in cookie validation feature to prevent cookie data from being tampered.

CSecurityManager is mainly used to protect data from being tampered and viewed. It can generate HMAC and encrypt the data. The private key used to generate HMAC is set by ValidationKey. The key used to encrypt data is specified by EncryptionKey. If the above keys are not explicitly set, random keys will be generated and used.

To protected data with HMAC, call hashData(); and to check if the data is tampered, call validateData(), which will return the real data if it is not tampered. The algorithm used to generated HMAC is specified by Validation.

To encrypt and decrypt data, call encrypt() and decrypt() respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt extension must be installed and loaded.

CSecurityManager is a core application component that can be accessed via CApplication::getSecurityManager().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
encryptionKey | string | the private key used to encrypt/decrypt data. | CSecurityManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
validation | string | hashing algorithm used to generate HMAC. | CSecurityManager
validationKey | string | the private key used to generate HMAC. | CSecurityManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
decrypt() | Decrypts data with EncryptionKey. | CSecurityManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
encrypt() | Encrypts data with EncryptionKey. | CSecurityManager
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEncryptionKey() |  | CSecurityManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getValidation() |  | CSecurityManager
getValidationKey() |  | CSecurityManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
hashData() | Prefixes data with an HMAC. | CSecurityManager
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent
setEncryptionKey() |  | CSecurityManager
setValidation() |  | CSecurityManager
setValidationKey() |  | CSecurityManager
validateData() | Validates if data is tampered. | CSecurityManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
computeHMAC() | Computes the HMAC for the data with ValidationKey. | CSecurityManager
generateRandomKey() |  | CSecurityManager

Property Details

encryptionKey property
public string getEncryptionKey()
public void setEncryptionKey(string $value)

the private key used to encrypt/decrypt data. If the key is not explicitly set, a random one is generated and returned.

validation property
public string getValidation()
public void setValidation(string $value)

hashing algorithm used to generate HMAC. Defaults to 'SHA1'.

validationKey property
public string getValidationKey()
public void setValidationKey(string $value)

the private key used to generate HMAC. If the key is not explicitly set, a random one is generated and returned.

Method Details

computeHMAC() method
protected string computeHMAC(string $data)
$data | string | data to be generated HMAC
{return} | string | the HMAC for the data

Computes the HMAC for the data with ValidationKey.

decrypt() method
public string decrypt(string $data)
$data | string | data to be decrypted.
{return} | string | the decrypted data

Decrypts data with EncryptionKey.

encrypt() method
public string encrypt(string $data)
$data | string | data to be encrypted.
{return} | string | the encrypted data

Encrypts data with EncryptionKey.

generateRandomKey() method
protected string generateRandomKey()
{return} string a randomly generated key

getEncryptionKey() method
public string getEncryptionKey()
{return} string the private key used to encrypt/decrypt data. If the key is not explicitly set, a random one is generated and returned.

getValidation() method
public string getValidation()
{return} string hashing algorithm used to generate HMAC. Defaults to 'SHA1'.

getValidationKey() method
public string getValidationKey()
{return} string the private key used to generate HMAC. If the key is not explicitly set, a random one is generated and returned.

hashData() method
public string hashData(string $data)
$data | string | data to be hashed.
{return} | string | data prefixed with HMAC

Prefixes data with an HMAC.

setEncryptionKey() method
public void setEncryptionKey(string $value)
$value string the key used to encrypt/decrypt data.

setValidation() method
public void setValidation(string $value)
$value string hashing algorithm used to generate HMAC. It must be either 'MD5' or 'SHA1'.

setValidationKey() method
public void setValidationKey(string $value)
$value string the key used to generate HMAC

validateData() method
public string validateData(string $data)
$data | string | data to be validated. The data must be previously generated using hashData().
{return} | string | the real data with HMAC stripped off. False if the data is tampered.

Validates if data is tampered.


CStatePersister

Package | system.base
Inheritance | class CStatePersister » CApplicationComponent » CComponent
Implements | IApplicationComponent, IStatePersister
Since | 1.0
Version | $Id: CStatePersister.php 1678 2010-01-07 21:02:00Z qiang.xue $
CStatePersister implements a file-based persistent data storage.

It can be used to keep data available through multiple requests and sessions.

By default, CStatePersister stores data in a file named 'state.bin' that is located under the application runtime path. You may change the location by setting the stateFile property.

To retrieve the data from CStatePersister, call load(). To save the data, call save().

Comparison among state persister, session and cache is as follows:
  • session: data persisting within a single user session.
  • state persister: data persisting through all requests/sessions (e.g. hit counter).
  • cache: volatile and fast storage. It may be used as storage medium for session or state persister.

Since server resource is often limited, be cautious if you plan to use CStatePersister to store large amount of data. You should also consider using database-based persister to improve the throughput.

CStatePersister is a core application component used to store global application state. It may be accessed via CApplication::getStatePersister). page state persistent method based on cache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component that is used to cache the state values. | CStatePersister
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
stateFile | string | the file path storing the state data. | CStatePersister

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the component. | CStatePersister
load() | Loads state data from persistent storage. | CStatePersister
raiseEvent() | Raises an event. | CComponent
save() | Saves application state in persistent storage. | CStatePersister

Property Details

cacheID property (available since v1.0.10)
public string $cacheID;

the ID of the cache application component that is used to cache the state values. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching state values.

stateFile property
public string $stateFile;

the file path storing the state data. Make sure the directory containing the file exists and is writable by the Web server process. If using relative path, also make sure the path is correct.

Method Details

init() method
public void init()

Initializes the component. This method overrides the parent implementation by making sure stateFile contains valid value.

load() method
public mixed load()
{return} mixed state data. Null if no state data available.

Loads state data from persistent storage.

save() method
public void save(mixed $state)
$state mixed state data (must be serializable).

Saves application state in persistent storage.


IAction

All Packages | Methods
Package | system.base
Inheritance | interface IAction
Subclasses | CAction, CCaptchaAction, CInlineAction, CViewAction, CWebServiceAction
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IAction is the interface that must be implemented by controller actions.

Public Methods

Hide inherited methods

Method | Description | Defined By
getController() |  | IAction
getId() |  | IAction
run() | Runs the action. | IAction

Method Details

getController() method
abstract public CController getController()
{return} CController the controller instance

getId() method
abstract public string getId()
{return} string id of the action

run() method
abstract public void run()

Runs the action. This method is invoked by the controller owning this action.


IApplicationComponent

All Packages | Methods
Package | system.base
Inheritance | interface IApplicationComponent
Subclasses | CApcCache, CApplicationComponent, CAssetManager, CAuthManager, CCache, CCacheHttpSession, CClientScript, CDbAuthManager, CDbCache, CDbConnection, CDbFixtureManager, CDbHttpSession, CDbMessageSource, CDummyCache, CEAcceleratorCache, CErrorHandler, CFileCache, CFormatter, CGettextMessageSource, CHttpRequest, CHttpSession, CLogRouter, CMemCache, CMessageSource, CPhpAuthManager, CPhpMessageSource, CPradoViewRenderer, CSecurityManager, CStatePersister, CThemeManager, CUrlManager, CViewRenderer, CWebUser, CWidgetFactory, CXCache, CZendDataCache
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IApplicationComponent is the interface that all application components must implement.

After the application completes configuration, it will invoke the init() method of every loaded application component.

Public Methods

Hide inherited methods

Method | Description | Defined By
getIsInitialized() |  | IApplicationComponent
init() | Initializes the application component. | IApplicationComponent

Method Details

getIsInitialized() method
abstract public boolean getIsInitialized()
{return} boolean whether the init() method has been invoked.

init() method
abstract public void init()

Initializes the application component. This method is invoked after the application completes configuration.


IAuthManager

All Packages | Methods
Package | system.base
Inheritance | interface IAuthManager
Subclasses | CAuthManager, CDbAuthManager, CPhpAuthManager
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IAuthManager interface is implemented by an auth manager application component.

An auth manager is mainly responsible for providing role-based access control (RBAC) service.

Public Methods

Hide inherited methods

Method | Description | Defined By
addItemChild() | Adds an item as a child of another item. | IAuthManager
assign() | Assigns an authorization item to a user. | IAuthManager
checkAccess() | Performs access check for the specified user. | IAuthManager
clearAll() | Removes all authorization data. | IAuthManager
clearAuthAssignments() | Removes all authorization assignments. | IAuthManager
createAuthItem() | Creates an authorization item. | IAuthManager
executeBizRule() | Executes a business rule. | IAuthManager
getAuthAssignment() | Returns the item assignment information. | IAuthManager
getAuthAssignments() | Returns the item assignments for the specified user. | IAuthManager
getAuthItem() | Returns the authorization item with the specified name. | IAuthManager
getAuthItems() | Returns the authorization items of the specific type and user. | IAuthManager
getItemChildren() | Returns the children of the specified item. | IAuthManager
hasItemChild() | Returns a value indicating whether a child exists within a parent. | IAuthManager
isAssigned() | Returns a value indicating whether the item has been assigned to the user. | IAuthManager
removeAuthItem() | Removes the specified authorization item. | IAuthManager
removeItemChild() | Removes a child from its parent. | IAuthManager
revoke() | Revokes an authorization assignment from a user. | IAuthManager
save() | Saves authorization data into persistent storage. | IAuthManager
saveAuthAssignment() | Saves the changes to an authorization assignment. | IAuthManager
saveAuthItem() | Saves an authorization item to persistent storage. | IAuthManager

Method Details

addItemChild() method
abstract public void addItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name

Adds an item as a child of another item.

assign() method
abstract public CAuthAssignment assign(string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
$bizRule | string | the business rule to be executed when checkAccess is called for this particular authorization item.
$data | mixed | additional data associated with this assignment
{return} | CAuthAssignment | the authorization assignment information.

Assigns an authorization item to a user.

checkAccess() method
abstract public boolean checkAccess(string $itemName, mixed $userId, array $params=array ( ))
$itemName | string | the name of the operation that need access check
$userId | mixed | the user ID. This should can be either an integer and a string representing the unique identifier of a user. See IWebUser::getId.
$params | array | name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by the user.

Performs access check for the specified user.

clearAll() method
abstract public void clearAll()

Removes all authorization data.

clearAuthAssignments() method
abstract public void clearAuthAssignments()

Removes all authorization assignments.

createAuthItem() method
abstract public CAuthItem createAuthItem(string $name, integer $type, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name. This must be a unique identifier.
$type | integer | the item type (0: operation, 1: task, 2: role).
$description | string | description of the item
$bizRule | string | business rule associated with the item. This is a piece of PHP code that will be executed when checkAccess is called for the item.
$data | mixed | additional data associated with the item.
{return} | CAuthItem | the authorization item

Creates an authorization item. An authorization item represents an action permission (e.g. creating a post). It has three types: operation, task and role. Authorization items form a hierarchy. Higher level items inheirt permissions representing by lower level items.

executeBizRule() method
abstract public whether executeBizRule(string $bizRule, array $params, mixed $data)
$bizRule | string | the business rule to be executed.
$params | array | additional parameters to be passed to the business rule when being executed.
$data | mixed | additional data that is associated with the corresponding authorization item or assignment
{return} | whether | the execution returns a true value. If the business rule is empty, it will also return true.

Executes a business rule. A business rule is a piece of PHP code that will be executed when checkAccess is called.

getAuthAssignment() method
abstract public CAuthAssignment getAuthAssignment(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | CAuthAssignment | the item assignment information. Null is returned if the item is not assigned to the user.

Returns the item assignment information.

getAuthAssignments() method
abstract public array getAuthAssignments(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | array | the item assignment information for the user. An empty array will be returned if there is no item assigned to the user.

Returns the item assignments for the specified user.

getAuthItem() method
abstract public CAuthItem getAuthItem(string $name)
$name | string | the name of the item
{return} | CAuthItem | the authorization item. Null if the item cannot be found.

Returns the authorization item with the specified name.

getAuthItems() method
abstract public array getAuthItems(integer $type=NULL, mixed $userId=NULL)
$type | integer | the item type (0: operation, 1: task, 2: role). Defaults to null, meaning returning all items regardless of their type.
$userId | mixed | the user ID. Defaults to null, meaning returning all items even if they are not assigned to a user.
{return} | array | the authorization items of the specific type.

Returns the authorization items of the specific type and user.

getItemChildren() method
abstract public array getItemChildren(mixed $itemName)
$itemName | mixed | the parent item name. This can be either a string or an array. The latter represents a list of item names (available since version 1.0.5).
{return} | array | all child items of the parent

Returns the children of the specified item.

hasItemChild() method
abstract public boolean hasItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the child exists

Returns a value indicating whether a child exists within a parent.

isAssigned() method
abstract public boolean isAssigned(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether the item has been assigned to the user.

Returns a value indicating whether the item has been assigned to the user.

removeAuthItem() method
abstract public boolean removeAuthItem(string $name)
$name | string | the name of the item to be removed
{return} | boolean | whether the item exists in the storage and has been removed

Removes the specified authorization item.

removeItemChild() method
abstract public boolean removeItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the removal is successful

Removes a child from its parent. Note, the child item is not deleted. Only the parent-child relationship is removed.

revoke() method
abstract public boolean revoke(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether removal is successful

Revokes an authorization assignment from a user.

save() method
abstract public void save()

Saves authorization data into persistent storage. If any change is made to the authorization data, please make sure you call this method to save the changed data into persistent storage.

saveAuthAssignment() method
abstract public void saveAuthAssignment(CAuthAssignment $assignment)
$assignment CAuthAssignment the assignment that has been changed.

Saves the changes to an authorization assignment.

saveAuthItem() method
abstract public void saveAuthItem(CAuthItem $item, string $oldName=NULL)
$item | CAuthItem | the item to be saved.
$oldName | string | the old item name. If null, it means the item name is not changed.

Saves an authorization item to persistent storage.


IBehavior

All Packages | Methods
Package | system.base
Inheritance | interface IBehavior
Subclasses | CActiveRecordBehavior, CBehavior, CModelBehavior, CTimestampBehavior
Since | 1.0.2
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IBehavior interfaces is implemented by all behavior classes.

A behavior is a way to enhance a component with additional methods that are defined in the behavior class and not available in the component class.

Public Methods

Hide inherited methods

Method | Description | Defined By
attach() | Attaches the behavior object to the component. | IBehavior
detach() | Detaches the behavior object from the component. | IBehavior
getEnabled() |  | IBehavior
setEnabled() |  | IBehavior

Method Details

attach() method
abstract public void attach(CComponent $component)
$component CComponent the component that this behavior is to be attached to.

Attaches the behavior object to the component.

detach() method
abstract public void detach(CComponent $component)
$component CComponent the component that this behavior is to be detached from.

Detaches the behavior object from the component.

getEnabled() method
abstract public boolean getEnabled()
{return} boolean whether this behavior is enabled

setEnabled() method
abstract public void setEnabled(boolean $value)
$value boolean whether this behavior is enabled


IFilter

All Packages | Methods
Package | system.base
Inheritance | interface IFilter
Subclasses | CAccessControlFilter, CContentDecorator, CFilter, CFilterWidget, CHtmlPurifier, CInlineFilter, CMarkdown, COutputCache, COutputProcessor, CTextHighlighter
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IFilter is the interface that must be implemented by action filters.

Public Methods

Hide inherited methods

Method | Description | Defined By
filter() | Performs the filtering. | IFilter

Method Details

filter() method
abstract public void filter(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

Performs the filtering. This method should be implemented to perform actual filtering. If the filter wants to continue the action execution, it should call $filterChain->run().


IStatePersister

All Packages | Methods
Package | system.base
Inheritance | interface IStatePersister
Subclasses | CStatePersister
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IStatePersister is the interface that must be implemented by state persister calsses.

This interface must be implemented by all state persister classes (such as CStatePersister.

Public Methods

Hide inherited methods

Method | Description | Defined By
load() | Loads state data from a persistent storage. | IStatePersister
save() | Saves state data into a persistent storage. | IStatePersister

Method Details

load() method
abstract public mixed load()
{return} mixed the state

Loads state data from a persistent storage.

save() method
abstract public void save(mixed $state)
$state mixed the state to be saved

Saves state data into a persistent storage.


IUserIdentity

All Packages | Methods
Package | system.base
Inheritance | interface IUserIdentity
Subclasses | CBaseUserIdentity, CUserIdentity
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IUserIdentity interface is implemented by a user identity class.

An identity represents a way to authenticate a user and retrieve information needed to uniquely identity the user. It is normally used with the user application component.

Public Methods

Hide inherited methods

Method | Description | Defined By
authenticate() | Authenticates the user. | IUserIdentity
getId() | Returns a value that uniquely represents the identity. | IUserIdentity
getIsAuthenticated() | Returns a value indicating whether the identity is authenticated. | IUserIdentity
getName() | Returns the display name for the identity (e.g. username). | IUserIdentity
getPersistentStates() | Returns the additional identity information that needs to be persistent during the user session. | IUserIdentity

Method Details

authenticate() method
abstract public boolean authenticate()
{return} boolean whether authentication succeeds.

Authenticates the user. The information needed to authenticate the user are usually provided in the constructor.

getId() method
abstract public mixed getId()
{return} mixed a value that uniquely represents the identity (e.g. primary key value).

Returns a value that uniquely represents the identity.

getIsAuthenticated() method
abstract public boolean getIsAuthenticated()
{return} boolean whether the identity is valid.

Returns a value indicating whether the identity is authenticated.

getName() method
abstract public string getName()
{return} string the display name for the identity.

Returns the display name for the identity (e.g. username).

getPersistentStates() method
abstract public array getPersistentStates()
{return} array additional identity information that needs to be persistent during the user session (excluding id).

Returns the additional identity information that needs to be persistent during the user session.


IViewRenderer

All Packages | Methods
Package | system.base
Inheritance | interface IViewRenderer
Subclasses | CPradoViewRenderer, CViewRenderer
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IViewRenderer interface is implemented by a view renderer class.

A view renderer is viewRenderer application component whose wants to replace the default view rendering logic implemented in CBaseController.

Public Methods

Hide inherited methods

Method | Description | Defined By
renderFile() | Renders a view file. | IViewRenderer

Method Details

renderFile() method
abstract public mixed renderFile(CBaseController $context, string $file, mixed $data, boolean $return)
$context | CBaseController | the controller or widget who is rendering the view file.
$file | string | the view file path
$data | mixed | the data to be passed to the view
$return | boolean | whether the rendering result should be returned
{return} | mixed | the rendering result, or null if the rendering result is not needed.

Renders a view file.


IWebServiceProvider

All Packages | Methods
Package | system.base
Inheritance | interface IWebServiceProvider
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IWebServiceProvider interface may be implemented by Web service provider classes.

If this interface is implemented, the provider instance will be able to intercept the remote method invocation (e.g. for logging or authentication purpose).

Public Methods

Hide inherited methods

Method | Description | Defined By
afterWebMethod() | This method is invoked after the requested remote method is invoked. | IWebServiceProvider
beforeWebMethod() | This method is invoked before the requested remote method is invoked. | IWebServiceProvider

Method Details

afterWebMethod() method
abstract public void afterWebMethod(CWebService $service)
$service CWebService the currently requested Web service.

This method is invoked after the requested remote method is invoked.

beforeWebMethod() method
abstract public boolean beforeWebMethod(CWebService $service)
$service | CWebService | the currently requested Web service.
{return} | boolean | whether the remote method should be executed.

This method is invoked before the requested remote method is invoked.


IWebUser

All Packages | Methods
Package | system.base
Inheritance | interface IWebUser
Subclasses | CWebUser
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IWebUser interface is implemented by a user application component.

A user application component represents the identity information for the current user.

Public Methods

Hide inherited methods

Method | Description | Defined By
checkAccess() | Performs access check for this user. | IWebUser
getId() | Returns a value that uniquely represents the identity. | IWebUser
getIsGuest() | Returns a value indicating whether the user is a guest (not authenticated). | IWebUser
getName() | Returns the display name for the identity (e.g. username). | IWebUser

Method Details

checkAccess() method
abstract public boolean checkAccess(string $operation, array $params=array ( ))
$operation | string | the name of the operation that need access check.
$params | array | name-value pairs that would be passed to business rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by this user.

Performs access check for this user.

getId() method
abstract public mixed getId()
{return} mixed a value that uniquely represents the identity (e.g. primary key value).

Returns a value that uniquely represents the identity.

getIsGuest() method
abstract public boolean getIsGuest()
{return} boolean whether the user is a guest (not authenticated)

Returns a value indicating whether the user is a guest (not authenticated).

getName() method
abstract public string getName()
{return} string the display name for the identity.

Returns the display name for the identity (e.g. username).


CApcCache

Package | system.caching
Inheritance | class CApcCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0
Version | $Id: CApcCache.php 1832 2010-02-20 03:22:45Z qiang.xue $
CApcCache provides APC caching in terms of an application component.

The caching is based on APC. To use this application component, the APC PHP extension must be loaded.

See CCache manual for common cache operations that are supported by CApcCache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CApcCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CApcCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CApcCache
deleteValue() | Deletes a value with the specified key from cache | CApcCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CApcCache
getValues() | Retrieves multiple values from cache with the specified keys. | CApcCache
setValue() | Stores a value identified by a key in cache. | CApcCache

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

getValues() method (available since v1.0.8)
protected array getValues(array $keys)
$keys | array | a list of keys identifying the cached values
{return} | array | a list of cached values indexed by the keys

Retrieves multiple values from cache with the specified keys.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It checks the availability of memcache.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CCache

Package | system.caching
Inheritance | abstract class CCache » CApplicationComponent » CComponent
Implements | IApplicationComponent, ICache, ArrayAccess
Subclasses | CApcCache, CDbCache, CEAcceleratorCache, CFileCache, CMemCache, CXCache, CZendDataCache
Since | 1.0
Version | $Id: CCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCache is the base class for cache classes with different cache storage implementation.

A data item can be stored in cache by calling set and be retrieved back later by get. In both operations, a key identifying the data item is required. An expiration time and/or a dependency can also be specified when calling set. If the data item expires or the dependency changes, calling get will not return back the data item.

Note, by definition, cache does not ensure the existence of a value even if it does not expire. Cache is not meant to be a persistent storage.

CCache implements the interface ICache with the following methods:
  • get : retrieve the value with a key (if any) from cache
  • set : store the value with a key into cache
  • add : store the value only if cache does not have this key
  • delete : delete the value with the specified key from cache
  • flush : delete all values from cache

Child classes must implement the following methods:
  • getValue
  • setValue
  • addValue
  • deleteValue
  • flush (optional)

CCache also implements ArrayAccess so that it can be used like an array.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
deleteValue() | Deletes a value with the specified key from cache | CCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CCache
getValues() | Retrieves multiple values from cache with the specified keys. | CCache
setValue() | Stores a value identified by a key in cache. | CCache

Property Details

keyPrefix property
public string $keyPrefix;

a string prefixed to every cache key so that it is unique. Defaults to application ID.

Method Details

add() method
public boolean add(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labeled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. Nothing will be done if the cache already contains the key.

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This method should be implemented by child classes to store the data in specific cache storage. The uniqueness and dependency are handled in add() already. So only the implementation of data storage is needed.

delete() method
public boolean delete(string $id)
$id | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This method should be implemented by child classes to delete the data from actual cache storage.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications. Child classes may implement this method to realize the flush operation.

generateUniqueKey() method
protected sring generateUniqueKey(string $key)
$key | string | a key identifying a value to be cached
{return} | sring | a key generated from the provided key which ensures the uniqueness across applications

get() method
public mixed get(string $id)
$id | string | a key identifying the cached value
{return} | mixed | the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.

Retrieves a value from cache with a specified key.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This method should be implemented by child classes to retrieve the data from specific cache storage. The uniqueness and dependency are handled in get() already. So only the implementation of data retrieval is needed.

getValues() method (available since v1.0.8)
protected array getValues(array $keys)
$keys | array | a list of keys identifying the cached values
{return} | array | a list of cached values indexed by the keys

Retrieves multiple values from cache with the specified keys. The default implementation simply calls getValue multiple times to retrieve the cached values one by one. If the underlying cache storage supports multiget, this method should be overridden to exploit that feature.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by setting default cache key prefix.

mget() method (available since v1.0.8)
public array mget(array $ids)
$ids | array | list of keys identifying the cached values
{return} | array | list of cached values corresponding to the specified keys. The array is returned in terms of (key,value) pairs. If a value is not cached or expired, the corresponding array value will be false.

Retrieves multiple values from cache with the specified keys. Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, which may improve the performance since it reduces the communication cost. In case a cache doesn't support this feature natively, it will be simulated by this method.

offsetExists() method
public boolean offsetExists(string $id)
$id | string | a key identifying the cached value
{return} | boolean |

Returns whether there is a cache entry with a specified key. This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(string $id)
$id | string | a key identifying the cached value
{return} | mixed | the value stored in cache, false if the value is not in the cache or expired.

Retrieves the value from cache with a specified key. This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(string $id, mixed $value)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached

Stores the value identified by a key into cache. If the cache already contains such a key, the existing value will be replaced with the new ones. To add expiration and dependencies, use the set() method. This method is required by the interface ArrayAccess.

offsetUnset() method
public boolean offsetUnset(string $id)
$id | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes the value with the specified key from cache This method is required by the interface ArrayAccess.

set() method
public boolean set(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labeled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache. If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This method should be implemented by child classes to store the data in specific cache storage. The uniqueness and dependency are handled in set() already. So only the implementation of data storage is needed.


CDbCache

Package | system.caching
Inheritance | class CDbCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0
Version | $Id: CDbCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbCache implements a cache application component by storing cached data in a database.

CDbCache stores cache data in a DB table named cacheTableName. If the table does not exist, it will be automatically created. By setting autoCreateCacheTable to false, you can also manually create the DB table.

CDbCache relies on PDO to access database. By default, it will use a SQLite3 database under the application runtime directory. You can also specify connectionID so that it makes use of a DB application component to access database.

See CCache manual for common cache operations that are supported by CDbCache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoCreateCacheTable | boolean | whether the cache DB table should be created automatically if it does not exist. | CDbCache
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheTableName | string | name of the DB table to store cache content. | CDbCache
connectionID | string | the ID of the CDbConnection application component. | CDbCache
gCProbability | integer | the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. | CDbCache
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | the DB connection instance | CDbCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__destruct() | Destructor. | CDbCache
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CDbCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getGCProbability() |  | CDbCache
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CDbCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache
setGCProbability() |  | CDbCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CDbCache
createCacheTable() | Creates the cache DB table. | CDbCache
deleteValue() | Deletes a value with the specified key from cache | CDbCache
gc() | Removes the expired data values. | CDbCache
generateUniqueKey() |  | CCache
getDbConnection() |  | CDbCache
getValue() | Retrieves a value from cache with a specified key. | CDbCache
getValues() | Retrieves multiple values from cache with the specified keys. | CDbCache
setValue() | Stores a value identified by a key in cache. | CDbCache

Property Details

autoCreateCacheTable property
public boolean $autoCreateCacheTable;

whether the cache DB table should be created automatically if it does not exist. Defaults to true. If you already have the table created, it is recommended you set this property to be false to improve performance.

See Also

  • cacheTableName
cacheTableName property
public string $cacheTableName;

name of the DB table to store cache content. Defaults to 'YiiCache'. Note, if autoCreateCacheTable is false and you want to create the DB table manually by yourself, you need to make sure the DB table is of the following structure:

(id CHAR(128) PRIMARY KEY, expire INTEGER, value BLOB)
Note, some DBMS might not support BLOB type. In this case, replace 'BLOB' with a suitable binary data type (e.g. LONGBLOB in MySQL, BYTEA in PostgreSQL.)

See Also

  • autoCreateCacheTable
connectionID property
public string $connectionID;

the ID of the CDbConnection application component. If not set, a SQLite3 database will be automatically created and used. The SQLite database file is protected/runtime/cache-YiiVersion.db.

dbConnection property read-only
protected CDbConnection getDbConnection()

the DB connection instance

gCProbability property (available since v1.0.9)
public integer getGCProbability()
public void setGCProbability(integer $value)

the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.

Method Details

__destruct() method
public void __destruct()

Destructor. Disconnect the db connection.

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

createCacheTable() method
protected void createCacheTable(CDbConnection $db, string $tableName)
$db | CDbConnection | the database connection
$tableName | string | the name of the table to be created

Creates the cache DB table.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

gc() method (available since v1.0.11)
protected void gc()

Removes the expired data values.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance

getGCProbability() method (available since v1.0.9)
public integer getGCProbability()
{return} integer the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

getValues() method (available since v1.0.8)
protected array getValues(array $keys)
$keys | array | a list of keys identifying the cached values
{return} | array | a list of cached values indexed by the keys

Retrieves multiple values from cache with the specified keys.

init() method
public void init()

Initializes this application component.

This method is required by the IApplicationComponent interface. It ensures the existence of the cache DB table. It also removes expired data items from the cache.

setGCProbability() method (available since v1.0.9)
public void setGCProbability(integer $value)
$value integer the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CDummyCache

Package | system.caching
Inheritance | class CDummyCache » CApplicationComponent » CComponent
Implements | IApplicationComponent, ICache, ArrayAccess
Since | 1.0
Version | $Id: CDummyCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDummyCache is a placeholder cache component.

CDummyCache does not do/cache anything. It is used as the default 'cache' application component.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CDummyCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CDummyCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CDummyCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CDummyCache
get() | Retrieves a value from cache with a specified key. | CDummyCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CDummyCache
mget() | Retrieves multiple values from cache with the specified keys. | CDummyCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CDummyCache
offsetGet() | Retrieves the value from cache with a specified key. | CDummyCache
offsetSet() | Stores the value identified by a key into cache. | CDummyCache
offsetUnset() | Deletes the value with the specified key from cache | CDummyCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CDummyCache

Property Details

keyPrefix property
public string $keyPrefix;

a string prefixed to every cache key so that it is unique. Defaults to application ID.

Method Details

add() method
public boolean add(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labeled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. Nothing will be done if the cache already contains the key.

delete() method
public boolean delete(string $id)
$id | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications. Child classes may implement this method to realize the flush operation.

get() method
public mixed get(string $id)
$id | string | a key identifying the cached value
{return} | mixed | the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.

Retrieves a value from cache with a specified key.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by setting default cache key prefix.

mget() method (available since v1.0.8)
public array mget(array $ids)
$ids | array | list of keys identifying the cached values
{return} | array | list of cached values corresponding to the specified keys. The array is returned in terms of (key,value) pairs. If a value is not cached or expired, the corresponding array value will be false.

Retrieves multiple values from cache with the specified keys. Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, which may improve the performance since it reduces the communication cost. In case a cache doesn't support this feature natively, it will be simulated by this method.

offsetExists() method
public boolean offsetExists(string $id)
$id | string | a key identifying the cached value
{return} | boolean |

Returns whether there is a cache entry with a specified key. This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(string $id)
$id | string | a key identifying the cached value
{return} | mixed | the value stored in cache, false if the value is not in the cache or expired.

Retrieves the value from cache with a specified key. This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(string $id, mixed $value)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached

Stores the value identified by a key into cache. If the cache already contains such a key, the existing value will be replaced with the new ones. To add expiration and dependencies, use the set() method. This method is required by the interface ArrayAccess.

offsetUnset() method
public boolean offsetUnset(string $id)
$id | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes the value with the specified key from cache This method is required by the interface ArrayAccess.

set() method
public boolean set(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labeled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache. If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones.


CEAcceleratorCache

Package | system.caching
Inheritance | class CEAcceleratorCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0.4
Version | $Id: CEAcceleratorCache.php 1854 2010-03-03 13:10:50Z qiang.xue $
CEAcceleratorCache implements a cache application module based on eaccelerator.

To use this application component, the eAccelerator PHP extension must be loaded.

See CCache manual for common cache operations that are supported by CEAccelerator.

Please note that as of v0.9.6, eAccelerator no longer supports data caching. This means if you still want to use this component, your eAccelerator should be of 0.9.5.x or lower version.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CEAcceleratorCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CEAcceleratorCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CEAcceleratorCache
deleteValue() | Deletes a value with the specified key from cache | CEAcceleratorCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CEAcceleratorCache
getValues() | Retrieves multiple values from cache with the specified keys. | CCache
setValue() | Stores a value identified by a key in cache. | CEAcceleratorCache

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It checks the availability of eAccelerator.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CFileCache

Package | system.caching
Inheritance | class CFileCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0.6
Version | $Id: CFileCache.php 1832 2010-02-20 03:22:45Z qiang.xue $
CFileCache provides a file-based caching mechanism.

For each data value being cached, CFileCache will use store it in a separate file under cachePath which defaults to 'protected/runtime/cache'. CFileCache will perform garbage collection automatically to remove expired cache files.

See CCache manual for common cache operations that are supported by CFileCache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheFileSuffix | string | cache file suffix. | CFileCache
cachePath | string | the directory to store cache files. | CFileCache
directoryLevel | integer | the level of sub-directories to store cache files. | CFileCache
gCProbability | integer | the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. | CFileCache
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CFileCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getGCProbability() |  | CFileCache
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CFileCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache
setGCProbability() |  | CFileCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CFileCache
deleteValue() | Deletes a value with the specified key from cache | CFileCache
gc() | Removes expired cache files. | CFileCache
generateUniqueKey() |  | CCache
getCacheFile() | Returns the cache file path given the cache key. | CFileCache
getValue() | Retrieves a value from cache with a specified key. | CFileCache
getValues() | Retrieves multiple values from cache with the specified keys. | CCache
setValue() | Stores a value identified by a key in cache. | CFileCache

Property Details

cacheFileSuffix property
public string $cacheFileSuffix;

cache file suffix. Defaults to '.bin'.

cachePath property
public string $cachePath;

the directory to store cache files. Defaults to null, meaning using 'protected/runtime/cache' as the directory.

directoryLevel property
public integer $directoryLevel;

the level of sub-directories to store cache files. Defaults to 0, meaning no sub-directories. If the system has huge number of cache files (e.g. 10K+), you may want to set this value to be 1 or 2 so that the file system is not over burdened. The value of this property should not exceed 16 (less than 3 is recommended).

gCProbability property
public integer getGCProbability()
public void setGCProbability(integer $value)

the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

gc() method
protected void gc(boolean $expiredOnly=true, string $path=NULL)
$expiredOnly | boolean | whether to removed expired cache files only. If true, all cache files under cachePath will be removed.
$path | string | the path to clean with. If null, it will be cachePath.

Removes expired cache files.

getCacheFile() method
protected string getCacheFile(string $key)
$key | string | cache key
{return} | string | the cache file path

Returns the cache file path given the cache key.

getGCProbability() method
public integer getGCProbability()
{return} integer the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It checks the availability of memcache.

setGCProbability() method
public void setGCProbability(integer $value)
$value integer the probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CMemCache

Package | system.caching
Inheritance | class CMemCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0
Version | $Id: CMemCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMemCache implements a cache application component based on memcached.

CMemCache can be configured with a list of memcache servers by settings its servers property. By default, CMemCache assumes there is a memcache server running on localhost at port 11211.

See CCache manual for common cache operations that are supported by CMemCache.

Note, there is no security measure to protected data in memcache. All data in memcache can be accessed by any process running in the system.

To use CMemCache as the cache application component, configure the application as follows,
array(
    'components'=>array(
        'cache'=>array(
            'class'=>'CMemCache',
            'servers'=>array(
                array(
                    'host'=>'server1',
                    'port'=>11211,
                    'weight'=>60,
                ),
                array(
                    'host'=>'server2',
                    'port'=>11211,
                    'weight'=>40,
                ),
            ),
        ),
    ),
)
In the above, two memcache servers are used: server1 and server2. You can configure more properties of every server, including: host, port, persistent, weight, timeout, retryInterval, status. See http://www.php.net/manual/en/function.memcache-addserver.php for more details.

Since version 1.0.6, CMemCache can also be used with memcached. To do so, set useMemcached to be true.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache
memCache | mixed | the memcache instance (or memcached if useMemcached is true) used by this component. | CMemCache
servers | array | list of memcache server configurations. | CMemCache
useMemcached | boolean | whether to use {@link http://pecl. | CMemCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CMemCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getMemCache() |  | CMemCache
getServers() |  | CMemCache
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CMemCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache
setServers() |  | CMemCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CMemCache
deleteValue() | Deletes a value with the specified key from cache | CMemCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CMemCache
getValues() | Retrieves multiple values from cache with the specified keys. | CMemCache
setValue() | Stores a value identified by a key in cache. | CMemCache

Property Details

memCache property read-only
public mixed getMemCache()

the memcache instance (or memcached if useMemcached is true) used by this component.

servers property
public array getServers()
public void setServers(array $config)

list of memcache server configurations. Each element is a CMemCacheServerConfiguration.

useMemcached property (available since v1.0.6)
public boolean $useMemcached;

whether to use memcached as the underlying caching extension. Defaults to false, meaning using memcache.

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

getMemCache() method
public mixed getMemCache()
{return} mixed the memcache instance (or memcached if useMemcached is true) used by this component.

getServers() method
public array getServers()
{return} array list of memcache server configurations. Each element is a CMemCacheServerConfiguration.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

getValues() method (available since v1.0.8)
protected array getValues(array $keys)
$keys | array | a list of keys identifying the cached values
{return} | array | a list of cached values indexed by the keys

Retrieves multiple values from cache with the specified keys.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It creates the memcache instance and adds memcache servers.

setServers() method
public void setServers(array $config)
$config array list of memcache server configurations. Each element must be an array with the following keys: host, port, persistent, weight, timeout, retryInterval, status.

See Also

  • http://www.php.net/manual/en/function.Memcache-addServer.php
setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CMemCacheServerConfiguration

Package | system.caching
Inheritance | class CMemCacheServerConfiguration » CComponent
Since | 1.0
Version | $Id: CMemCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMemCacheServerConfiguration represents the configuration data for a single memcache server.

See http://www.php.net/manual/en/function.Memcache-addServer.php for detailed explanation of each configuration property.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
host | string | memcache server hostname or IP address | CMemCacheServerConfiguration
persistent | boolean | whether to use a persistent connection | CMemCacheServerConfiguration
port | integer | memcache server port | CMemCacheServerConfiguration
retryInterval | integer | how often a failed server will be retried (in seconds) | CMemCacheServerConfiguration
status | boolean | if the server should be flagged as online upon a failure | CMemCacheServerConfiguration
timeout | integer | value in seconds which will be used for connecting to the server | CMemCacheServerConfiguration
weight | integer | probability of using this server among all servers. | CMemCacheServerConfiguration

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CMemCacheServerConfiguration
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

host property
public string $host;

memcache server hostname or IP address

persistent property
public boolean $persistent;

whether to use a persistent connection

port property
public integer $port;

memcache server port

retryInterval property
public integer $retryInterval;

how often a failed server will be retried (in seconds)

status property
public boolean $status;

if the server should be flagged as online upon a failure

timeout property
public integer $timeout;

value in seconds which will be used for connecting to the server

weight property
public integer $weight;

probability of using this server among all servers.

Method Details

__construct() method
public void __construct(array $config)
$config array list of memcache server configurations.

Constructor.


CXCache

Package | system.caching
Inheritance | class CXCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0.1
Version | $Id: CXCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CXCache implements a cache application module based on xcache.

To use this application component, the XCache PHP extension must be loaded.

See CCache manual for common cache operations that are supported by CXCache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CXCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CXCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CXCache
deleteValue() | Deletes a value with the specified key from cache | CXCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CXCache
getValues() | Retrieves multiple values from cache with the specified keys. | CCache
setValue() | Stores a value identified by a key in cache. | CXCache

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It checks the availability of memcache.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


CZendDataCache

Package | system.caching
Inheritance | class CZendDataCache » CCache » CApplicationComponent » CComponent
Implements | ArrayAccess, ICache, IApplicationComponent
Since | 1.0.4
Version | $Id: CZendDataCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
CZendDataCache implements a cache application module based on the Zend Data Cache delivered with ZendServer.

To use this application component, the Zend Data Cache PHP extension must be loaded.

See CCache manual for common cache operations that are supported by CZendDataCache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
keyPrefix | string | a string prefixed to every cache key so that it is unique. | CCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Stores a value identified by a key into cache if the cache does not contain this key. | CCache
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
delete() | Deletes a value with the specified key from cache | CCache
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Deletes all values from cache. | CZendDataCache
get() | Retrieves a value from cache with a specified key. | CCache
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CZendDataCache
mget() | Retrieves multiple values from cache with the specified keys. | CCache
offsetExists() | Returns whether there is a cache entry with a specified key. | CCache
offsetGet() | Retrieves the value from cache with a specified key. | CCache
offsetSet() | Stores the value identified by a key into cache. | CCache
offsetUnset() | Deletes the value with the specified key from cache | CCache
raiseEvent() | Raises an event. | CComponent
set() | Stores a value identified by a key into cache. | CCache

Protected Methods

Hide inherited methods

Method | Description | Defined By
addValue() | Stores a value identified by a key into cache if the cache does not contain this key. | CZendDataCache
deleteValue() | Deletes a value with the specified key from cache | CZendDataCache
generateUniqueKey() |  | CCache
getValue() | Retrieves a value from cache with a specified key. | CZendDataCache
getValues() | Retrieves multiple values from cache with the specified keys. | CCache
setValue() | Stores a value identified by a key in cache. | CZendDataCache

Method Details

addValue() method
protected boolean addValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. This is the implementation of the method declared in the parent class.

deleteValue() method
protected boolean deleteValue(string $key)
$key | string | the key of the value to be deleted
{return} | boolean | if no error happens during deletion

Deletes a value with the specified key from cache This is the implementation of the method declared in the parent class.

flush() method
public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

getValue() method
protected string getValue(string $key)
$key | string | a unique key identifying the cached value
{return} | string | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key. This is the implementation of the method declared in the parent class.

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface. It checks the availability of Zend Data Cache.

setValue() method
protected boolean setValue(string $key, string $value, integer $expire)
$key | string | the key identifying the value to be cached
$value | string | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.


ICache

All Packages | Methods
Package | system.caching
Inheritance | interface ICache
Subclasses | CApcCache, CCache, CDbCache, CDummyCache, CEAcceleratorCache, CFileCache, CMemCache, CXCache, CZendDataCache
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
ICache is the interface that must be implemented by cache components.

This interface must be implemented by classes supporting caching feature.

Public Methods

Hide inherited methods

Method | Description | Defined By
add() | Stores a value identified by a key into cache if the cache does not contain this key. | ICache
delete() | Deletes a value with the specified key from cache | ICache
flush() | Deletes all values from cache. | ICache
get() | Retrieves a value from cache with a specified key. | ICache
mget() | Retrieves multiple values from cache with the specified keys. | ICache
set() | Stores a value identified by a key into cache. | ICache

Method Details

add() method
abstract public boolean add(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labelled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache if the cache does not contain this key. Nothing will be done if the cache already contains the key.

delete() method
abstract public boolean delete(string $id)
$id | string | the key of the value to be deleted
{return} | boolean | whether the deletion is successful

Deletes a value with the specified key from cache

flush() method
abstract public void flush()

Deletes all values from cache. Be careful of performing this operation if the cache is shared by multiple applications.

get() method
abstract public mixed get(string $id)
$id | string | a key identifying the cached value
{return} | mixed | the value stored in cache, false if the value is not in the cache or expired.

Retrieves a value from cache with a specified key.

mget() method (available since v1.0.8)
abstract public array mget(array $ids)
$ids | array | list of keys identifying the cached values
{return} | array | list of cached values corresponding to the specified keys. The array is returned in terms of (key,value) pairs. If a value is not cached or expired, the corresponding array value will be false.

Retrieves multiple values from cache with the specified keys. Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, which may improve the performance since it reduces the communication cost. In case a cache doesn't support this feature natively, it will be simulated by this method.

set() method
abstract public boolean set(string $id, mixed $value, integer $expire=0, ICacheDependency $dependency=NULL)
$id | string | the key identifying the value to be cached
$value | mixed | the value to be cached
$expire | integer | the number of seconds in which the cached value will expire. 0 means never expire.
$dependency | ICacheDependency | dependency of the cached item. If the dependency changes, the item is labelled invalid.
{return} | boolean | true if the value is successfully stored into cache, false otherwise

Stores a value identified by a key into cache. If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones.


ICacheDependency

All Packages | Methods
Package | system.caching
Inheritance | interface ICacheDependency
Subclasses | CCacheDependency, CChainedCacheDependency, CDbCacheDependency, CDirectoryCacheDependency, CExpressionDependency, CFileCacheDependency, CGlobalStateCacheDependency
Since | 1.0
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
ICacheDependency is the interface that must be implemented by cache dependency classes.

This interface must be implemented by classes meant to be used as cache dependencies.

Objects implementing this interface must be able to be serialized and unserialized.

Public Methods

Hide inherited methods

Method | Description | Defined By
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | ICacheDependency
getHasChanged() |  | ICacheDependency

Method Details

evaluateDependency() method
abstract public void evaluateDependency()

Evaluates the dependency by generating and saving the data related with dependency. This method is invoked by cache before writing data into it.

getHasChanged() method
abstract public boolean getHasChanged()
{return} boolean whether the dependency has changed.


CCacheDependency

Package | system.caching.dependencies
Inheritance | class CCacheDependency » CComponent
Implements | ICacheDependency
Subclasses | CDbCacheDependency, CDirectoryCacheDependency, CExpressionDependency, CFileCacheDependency, CGlobalStateCacheDependency
Since | 1.0
Version | $Id: CCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCacheDependency is the base class for cache dependency classes.

CCacheDependency implements the ICacheDependency interface. Child classes should override its generateDependentData for actual dependency checking.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CCacheDependency

Property Details

dependentData property read-only
public mixed getDependentData()

the data used to determine if dependency has been changed. This data is available after evaluateDependency is called.

hasChanged property read-only
public boolean getHasChanged()

whether the dependency has changed.

Method Details

evaluateDependency() method
public void evaluateDependency()

Evaluates the dependency by generating and saving the data related with dependency. This method is invoked by cache before writing data into it.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. Derived classes should override this method to generate actual dependent data.

getDependentData() method
public mixed getDependentData()
{return} mixed the data used to determine if dependency has been changed. This data is available after evaluateDependency is called.

getHasChanged() method
public boolean getHasChanged()
{return} boolean whether the dependency has changed.


CChainedCacheDependency

Package | system.caching.dependencies
Inheritance | class CChainedCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CChainedCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CChainedCacheDependency represents a list of cache dependencies.

If any of the dependencies reports a dependency change, CChainedCacheDependency will return true for the checking.

To add dependencies to CChainedCacheDependency, use Dependencies which gives a CTypedList instance and can be used like an array (see CList for more details}).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependencies | CTypedList | list of dependency objects | CChainedCacheDependency
hasChanged | boolean | Performs the actual dependency checking. | CChainedCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CChainedCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependencies() |  | CChainedCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() | Performs the actual dependency checking. | CChainedCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setDependencies() |  | CChainedCacheDependency

Property Details

dependencies property
public CTypedList getDependencies()
public void setDependencies(array $values)

list of dependency objects

hasChanged property read-only
public boolean getHasChanged()

Performs the actual dependency checking. This method returns true if any of the dependency objects reports a dependency change.

Method Details

evaluateDependency() method
public void evaluateDependency()

Evaluates the dependency by generating and saving the data related with dependency.

getDependencies() method
public CTypedList getDependencies()
{return} CTypedList list of dependency objects

getHasChanged() method
public boolean getHasChanged()
{return} boolean whether the dependency is changed or not.

Performs the actual dependency checking. This method returns true if any of the dependency objects reports a dependency change.

setDependencies() method (available since v1.0.10)
public void setDependencies(array $values)
$values array list of dependency objects to be added to this chain.


CDbCacheDependency

Package | system.caching.dependencies
Inheritance | class CDbCacheDependency » CCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CDbCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbCacheDependency represents a dependency based on the query result of a SQL statement.

If the query result (a scalar) changes, the dependency is considered as changed. To specify the SQL statement, set sql property. The connectionID property specifies the ID of a CDbConnection application component. It is this DB connection that is used to perform the query.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
connectionID | string | the ID of a CDbConnection application component. | CDbCacheDependency
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency
sql | string | the SQL statement whose result is used to determine if the dependency has been changed. | CDbCacheDependency

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | the DB connection instance | CDbCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbCacheDependency
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__sleep() | PHP sleep magic method. | CDbCacheDependency
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CDbCacheDependency
getDbConnection() |  | CDbCacheDependency

Property Details

connectionID property
public string $connectionID;

the ID of a CDbConnection application component. Defaults to 'db'.

dbConnection property read-only
protected CDbConnection getDbConnection()

the DB connection instance

sql property
public string $sql;

the SQL statement whose result is used to determine if the dependency has been changed. Note, the SQL statement should return back a single value.

Method Details

__construct() method
public void __construct(string $sql=NULL)
$sql string the SQL statement whose result is used to determine if the dependency has been changed.

Constructor.

__sleep() method
public void __sleep()

PHP sleep magic method. This method ensures that the database instance is set null because it contains resource handles.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. This method returns the value of the global state.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance


CDirectoryCacheDependency

Package | system.caching.dependencies
Inheritance | class CDirectoryCacheDependency » CCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CDirectoryCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDirectoryCacheDependency represents a dependency based on change of a directory.

CDirectoryCacheDependency performs dependency checking based on the modification time of the files contained in the specified directory. The directory being checked is specified via directory.

By default, all files under the specified directory and subdirectories will be checked. If the last modification time of any of them is changed or if different number of files are contained in a directory, the dependency is reported as changed. By specifying recursiveLevel, one can limit the checking to a certain depth of the directory.

Note, dependency checking for a directory is expensive because it involves accessing modification time of multiple files under the directory.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
directory | string | the directory whose change is used to determine if the dependency has been changed. | CDirectoryCacheDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency
namePattern | string | the regular expression matching valid file/directory names. | CDirectoryCacheDependency
recursiveLevel | integer | the depth of the subdirectories to be recursively checked. | CDirectoryCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDirectoryCacheDependency
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CDirectoryCacheDependency
generateTimestamps() | Determines the last modification time for files under the directory. | CDirectoryCacheDependency
validateDirectory() | Checks to see if the specified subdirectory should be checked for dependency. | CDirectoryCacheDependency
validateFile() | Checks to see if the file should be checked for dependency. | CDirectoryCacheDependency

Property Details

directory property
public string $directory;

the directory whose change is used to determine if the dependency has been changed. If any of the files under the directory is changed, the dependency is considered as changed.

namePattern property
public string $namePattern;

the regular expression matching valid file/directory names. Only the matching files or directories will be checked for changes. Defaults to null, meaning all files/directories will qualify.

recursiveLevel property
public integer $recursiveLevel;

the depth of the subdirectories to be recursively checked. If the value is less than 0, it means unlimited depth. If the value is 0, it means checking the files directly under the specified directory.

Method Details

__construct() method
public void __construct(string $directory=NULL)
$directory string the directory to be checked

Constructor.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. This method returns the modification timestamps for files under the directory.

generateTimestamps() method
protected array generateTimestamps(string $directory, int $level=0)
$directory | string | the directory name
$level | int | level of the recursion
{return} | array | list of file modification time indexed by the file path

Determines the last modification time for files under the directory. This method may go recursively into subdirectories if recursiveLevel is not 0.

validateDirectory() method
protected boolean validateDirectory(string $directory)
$directory | string | the name of the subdirectory that may be checked for dependency.
{return} | boolean | whether this subdirectory should be checked.

Checks to see if the specified subdirectory should be checked for dependency. This method is invoked when dependency of the whole directory is being checked. By default, it always returns true, meaning the subdirectory should be checked. You may override this method to check only certain subdirectories.

validateFile() method
protected boolean validateFile(string $fileName)
$fileName | string | the name of the file that may be checked for dependency.
{return} | boolean | whether this file should be checked.

Checks to see if the file should be checked for dependency. This method is invoked when dependency of the whole directory is being checked. By default, it always returns true, meaning the file should be checked. You may override this method to check only certain files.


CExpressionDependency

Package | system.caching.dependencies
Inheritance | class CExpressionDependency » CCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CExpressionDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CExpressionDependency represents a dependency based on the result of a PHP expression.

CExpressionDependency performs dependency checking based on the result of a PHP expression. The dependency is reported as unchanged if and only if the result is the same as the one evaluated when storing the data to cache.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
expression | string | the PHP expression whose result is used to determine the dependency. | CExpressionDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CExpressionDependency
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CExpressionDependency

Property Details

expression property
public string $expression;

the PHP expression whose result is used to determine the dependency. Starting from version 1.0.11, the expression can also be a valid PHP callback, including class method name (array(ClassName/Object, MethodName)), or anonymous function (PHP 5.3.0+). The function/method will be passed with a parameter which is the dependency object itself.

Method Details

__construct() method
public void __construct(string $expression='true')
$expression string the PHP expression whose result is used to determine the dependency.

Constructor.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. This method returns the result of the PHP expression.


CFileCacheDependency

Package | system.caching.dependencies
Inheritance | class CFileCacheDependency » CCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CFileCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFileCacheDependency represents a dependency based on a file's last modification time.

CFileCacheDependency performs dependency checking based on the last modification time of the file specified via fileName. The dependency is reported as unchanged if and only if the file's last modification time remains unchanged.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
fileName | string | the name of the file whose last modification time is used to check if the dependency has been changed. | CFileCacheDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFileCacheDependency
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CFileCacheDependency

Property Details

fileName property
public string $fileName;

the name of the file whose last modification time is used to check if the dependency has been changed.

Method Details

__construct() method
public void __construct(string $fileName=NULL)
$fileName string name of the file whose change is to be checked.

Constructor.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. This method returns the file's last modification time.


CGlobalStateCacheDependency

Package | system.caching.dependencies
Inheritance | class CGlobalStateCacheDependency » CCacheDependency » CComponent
Implements | ICacheDependency
Since | 1.0
Version | $Id: CGlobalStateCacheDependency.php 1678 2010-01-07 21:02:00Z qiang.xue $
CGlobalStateCacheDependency represents a dependency based on a global state value.

CGlobalStateCacheDependency checks if a global state is changed or not. If the global state is changed, the dependency is reported as changed. To specify which global state this dependency should check with, set stateName to the name of the global state.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dependentData | mixed | the data used to determine if dependency has been changed. | CCacheDependency
hasChanged | boolean | whether the dependency has changed. | CCacheDependency
stateName | string | the name of the global state whose value is to check if the dependency has changed. | CGlobalStateCacheDependency

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGlobalStateCacheDependency
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateDependency() | Evaluates the dependency by generating and saving the data related with dependency. | CCacheDependency
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDependentData() |  | CCacheDependency
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasChanged() |  | CCacheDependency
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateDependentData() | Generates the data needed to determine if dependency has been changed. | CGlobalStateCacheDependency

Property Details

stateName property
public string $stateName;

the name of the global state whose value is to check if the dependency has changed.

See Also

  • CApplication::setGlobalState

Method Details

__construct() method
public void __construct(string $name=NULL)
$name string the name of the global state

Constructor.

generateDependentData() method
protected mixed generateDependentData()
{return} mixed the data needed to determine if dependency has been changed.

Generates the data needed to determine if dependency has been changed. This method returns the value of the global state.


CAttributeCollection

Package | system.collections
Inheritance | class CAttributeCollection » CMap » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CAttributeCollection.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAttributeCollection implements a collection for storing attribute names and values.

Besides all functionalities provided by CMap, CAttributeCollection allows you to get and set attribute values like getting and setting properties. For example, the following usages are all valid for a CAttributeCollection object:
$collection->text='text'; // same as:  $collection->add('text','text');
echo $collection->text;   // same as:  echo $collection->itemAt('text');

The case sensitivity of attribute names can be toggled by setting the caseSensitive property of the collection.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
caseSensitive | boolean | whether the keys are case-sensitive. | CAttributeCollection
count | integer | the number of items in the map | CMap
iterator | CMapIterator | Returns an iterator for traversing the items in the list. | CMap
keys | array | the key list | CMap
readOnly | boolean | whether this map is read-only or not. | CMap

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CMap
__get() | Returns a property value or an event handler list by property or event name. | CAttributeCollection
__isset() | Checks if a property value is null. | CAttributeCollection
__set() | Sets value of a component property. | CAttributeCollection
__unset() | Sets a component property to be null. | CAttributeCollection
add() | Adds an item into the map. | CAttributeCollection
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CAttributeCollection
canSetProperty() | Determines whether a property can be set. | CAttributeCollection
clear() | Removes all items in the map. | CMap
contains() | Returns whether the specified is in the map. | CAttributeCollection
copyFrom() | Copies iterable data into the map. | CMap
count() | Returns the number of items in the map. | CMap
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CMap
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CMap
getKeys() |  | CMap
getReadOnly() |  | CMap
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CAttributeCollection
itemAt() | Returns the item with the specified key. | CAttributeCollection
mergeArray() | Merges two arrays into one recursively. | CMap
mergeWith() | Merges iterable data into the map. | CMap
offsetExists() | Returns whether there is an element at the specified offset. | CMap
offsetGet() | Returns the element at the specified offset. | CMap
offsetSet() | Sets the element at the specified offset. | CMap
offsetUnset() | Unsets the element at the specified offset. | CMap
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the map by its key. | CAttributeCollection
toArray() |  | CMap

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CMap

Property Details

caseSensitive property
public boolean $caseSensitive;

whether the keys are case-sensitive. Defaults to false.

Method Details

__get() method
public mixed __get(string $name)
$name | string | the property name or the event name
{return} | mixed | the property value or the event handler list

Returns a property value or an event handler list by property or event name. This method overrides the parent implementation by returning a key value if the key exists in the collection.

__isset() method (available since v1.0.1)
public boolean __isset(string $name)
$name | string | the property name or the event name
{return} | boolean | whether the property value is null

Checks if a property value is null. This method overrides the parent implementation by checking if the key exists in the collection and contains a non-null value.

__set() method
public void __set(string $name, mixed $value)
$name | string | the property name or event name
$value | mixed | the property value or event handler

Sets value of a component property. This method overrides the parent implementation by adding a new key value to the collection.

__unset() method (available since v1.0.1)
public void __unset(string $name)
$name string the property name or the event name

Sets a component property to be null. This method overrides the parent implementation by clearing the specified key value.

add() method
public void add(mixed $key, mixed $value)
$key | mixed | key
$value | mixed | value

Adds an item into the map. This overrides the parent implementation by converting the key to lower case first if caseSensitive is false.

canGetProperty() method
public boolean canGetProperty(string $name)
$name | string | the property name
{return} | boolean | whether the property can be read

Determines whether a property can be read. This method overrides parent implementation by returning true if the collection contains the named key.

canSetProperty() method
public boolean canSetProperty(string $name)
$name | string | the property name
{return} | boolean | true

Determines whether a property can be set. This method overrides parent implementation by always returning true because you can always add a new value to the collection.

contains() method
public boolean contains(mixed $key)
$key | mixed | the key
{return} | boolean | whether the map contains an item with the specified key

Returns whether the specified is in the map. This overrides the parent implementation by converting the key to lower case first if caseSensitive is false.

hasProperty() method
public boolean hasProperty(string $name)
$name | string | the property name
{return} | boolean | whether the property is defined

Determines whether a property is defined. This method overrides parent implementation by returning true if the collection contains the named key.

itemAt() method
public mixed itemAt(mixed $key)
$key | mixed | the key
{return} | mixed | the element at the offset, null if no element is found at the offset

Returns the item with the specified key. This overrides the parent implementation by converting the key to lower case first if caseSensitive is false.

remove() method
public mixed remove(mixed $key)
$key | mixed | the key of the item to be removed
{return} | mixed | the removed value, null if no such key exists.

Removes an item from the map by its key. This overrides the parent implementation by converting the key to lower case first if caseSensitive is false.


CConfiguration

Package | system.collections
Inheritance | class CConfiguration » CMap » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CConfiguration.php 1678 2010-01-07 21:02:00Z qiang.xue $
CConfiguration represents an array-based configuration.

It can be used to initialize an object's properties.

The configuration data may be obtained from a PHP script. For example,
<?php
return array
(
    'name'=>'My Application',
    'defaultController'=>'index',
);
?>
Use the following code to load the above configuration data:
$config=new CConfiguration('path/to/config.php');

To apply the configuration to an object, call applyTo(). Each (key,value) pair in the configuration data is applied to the object like: $object->$key=$value.

Since CConfiguration extends from CMap, it can be used like an associative array. See CMap for more details.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the map | CMap
iterator | CMapIterator | Returns an iterator for traversing the items in the list. | CMap
keys | array | the key list | CMap
readOnly | boolean | whether this map is read-only or not. | CMap

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CConfiguration
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds an item into the map. | CMap
applyTo() | Applies the configuration to an object. | CConfiguration
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the map. | CMap
contains() |  | CMap
copyFrom() | Copies iterable data into the map. | CMap
count() | Returns the number of items in the map. | CMap
createObject() | Creates an object and initializes it based on the given configuration. | CConfiguration
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CMap
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CMap
getKeys() |  | CMap
getReadOnly() |  | CMap
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
itemAt() | Returns the item with the specified key. | CMap
loadFromFile() | Loads configuration data from a file and merges it with the existing configuration. | CConfiguration
mergeArray() | Merges two arrays into one recursively. | CMap
mergeWith() | Merges iterable data into the map. | CMap
offsetExists() | Returns whether there is an element at the specified offset. | CMap
offsetGet() | Returns the element at the specified offset. | CMap
offsetSet() | Sets the element at the specified offset. | CMap
offsetUnset() | Unsets the element at the specified offset. | CMap
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the map by its key. | CMap
saveAsString() | Saves the configuration into a string. | CConfiguration
toArray() |  | CMap

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CMap

Method Details

__construct() method
public void __construct(mixed $data=NULL)
$data mixed if string, it represents a config file (a PHP script returning the configuration as an array); If array, it is config data.

Constructor.

applyTo() method
public void applyTo(object $object)
$object object object to be applied with this configuration

Applies the configuration to an object. Each (key,value) pair in the configuration data is applied to the object like: $object->$key=$value.

createObject() method
public static mixed createObject(mixed $config)
$config | mixed | the configuration. It can be either a string or an array.
{return} | mixed | the created object

Creates an object and initializes it based on the given configuration.

NOTE: this method has been deprecated since version 1.0.1. Please use Yii::createComponent, instead.

loadFromFile() method
public void loadFromFile(string $configFile)
$configFile string configuration file path (if using relative path, be aware of what is the current path)

Loads configuration data from a file and merges it with the existing configuration.

A config file must be a PHP script returning a configuration array (like the following)

return array
(
    'name'=>'My Application',
    'defaultController'=>'index',
);

See Also

  • mergeWith
saveAsString() method
public string saveAsString()
{return} string the string representation of the configuration

Saves the configuration into a string. The string is a valid PHP expression representing the configuration data as an array.


CList

Package | system.collections
Inheritance | class CList » CComponent
Implements | IteratorAggregate, Traversable, ArrayAccess, Countable
Subclasses | CFilterChain, CTypedList
Since | 1.0
Version | $Id: CList.php 1678 2010-01-07 21:02:00Z qiang.xue $
CList implements an integer-indexed collection class.

You can access, append, insert, remove an item by using itemAt, add, insertAt, remove, and removeAt. To get the number of the items in the list, use getCount. CList can also be used like a regular array as follows,
$list[]=$item;  // append at the end
$list[$index]=$item; // $index must be between 0 and $list->Count
unset($list[$index]); // remove the item at $index
if(isset($list[$index])) // if the list has an item at $index
foreach($list as $index=>$item) // traverse each item in the list
$n=count($list); // returns the number of items in the list

To extend CList by doing additional operations with each addition or removal operation (e.g. performing type check), override insertAt(), and removeAt().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the list | CList
iterator | Iterator | Returns an iterator for traversing the items in the list. | CList
readOnly | boolean | whether this list is read-only or not. | CList

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CList
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Appends an item at the end of the list. | CList
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the list. | CList
contains() |  | CList
copyFrom() | Copies iterable data into the list. | CList
count() | Returns the number of items in the list. | CList
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CList
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CList
getReadOnly() |  | CList
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
indexOf() |  | CList
insertAt() | Inserts an item at the specified position. | CList
itemAt() | Returns the item at the specified offset. | CList
mergeWith() | Merges iterable data into the map. | CList
offsetExists() | Returns whether there is an item at the specified offset. | CList
offsetGet() | Returns the item at the specified offset. | CList
offsetSet() | Sets the item at the specified offset. | CList
offsetUnset() | Unsets the item at the specified offset. | CList
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the list. | CList
removeAt() | Removes an item at the specified position. | CList
toArray() |  | CList

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CList

Property Details

count property read-only
public integer getCount()

the number of items in the list

iterator property read-only
public Iterator getIterator()

Returns an iterator for traversing the items in the list. This method is required by the interface IteratorAggregate.

readOnly property
public boolean getReadOnly()
protected void setReadOnly(boolean $value)

whether this list is read-only or not. Defaults to false.

Method Details

__construct() method
public void __construct(array $data=NULL, boolean $readOnly=false)
$data | array | the initial data. Default is null, meaning no initialization.
$readOnly | boolean | whether the list is read-only

Constructor. Initializes the list with an array or an iterable object.

add() method
public integer add(mixed $item)
$item | mixed | new item
{return} | integer | the zero-based index at which the item is added

Appends an item at the end of the list.

clear() method
public void clear()

Removes all items in the list.

contains() method
public boolean contains(mixed $item)
$item | mixed | the item
{return} | boolean | whether the list contains the item

copyFrom() method
public void copyFrom(mixed $data)
$data mixed the data to be copied from, must be an array or object implementing Traversable

Copies iterable data into the list. Note, existing data in the list will be cleared first.

count() method
public integer count()
{return} integer number of items in the list.

Returns the number of items in the list. This method is required by Countable interface.

getCount() method
public integer getCount()
{return} integer the number of items in the list

getIterator() method
public Iterator getIterator()
{return} Iterator an iterator for traversing the items in the list.

Returns an iterator for traversing the items in the list. This method is required by the interface IteratorAggregate.

getReadOnly() method
public boolean getReadOnly()
{return} boolean whether this list is read-only or not. Defaults to false.

indexOf() method
public integer indexOf(mixed $item)
$item | mixed | the item
{return} | integer | the index of the item in the list (0 based), -1 if not found.

insertAt() method
public void insertAt(integer $index, mixed $item)
$index | integer | the specified position.
$item | mixed | new item

Inserts an item at the specified position. Original item at the position and the next items will be moved one step towards the end.

itemAt() method
public mixed itemAt(integer $index)
$index | integer | the index of the item
{return} | mixed | the item at the index

Returns the item at the specified offset. This method is exactly the same as offsetGet.

mergeWith() method
public void mergeWith(mixed $data)
$data mixed the data to be merged with, must be an array or object implementing Traversable

Merges iterable data into the map. New data will be appended to the end of the existing data.

offsetExists() method
public boolean offsetExists(integer $offset)
$offset | integer | the offset to check on
{return} | boolean |

Returns whether there is an item at the specified offset. This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(integer $offset)
$offset | integer | the offset to retrieve item.
{return} | mixed | the item at the offset

Returns the item at the specified offset. This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(integer $offset, mixed $item)
$offset | integer | the offset to set item
$item | mixed | the item value

Sets the item at the specified offset. This method is required by the interface ArrayAccess.

offsetUnset() method
public void offsetUnset(integer $offset)
$offset integer the offset to unset item

Unsets the item at the specified offset. This method is required by the interface ArrayAccess.

remove() method
public integer remove(mixed $item)
$item | mixed | the item to be removed.
{return} | integer | the index at which the item is being removed

Removes an item from the list. The list will first search for the item. The first item found will be removed from the list.

removeAt() method
public mixed removeAt(integer $index)
$index | integer | the index of the item to be removed.
{return} | mixed | the removed item.

Removes an item at the specified position.

setReadOnly() method
protected void setReadOnly(boolean $value)
$value boolean whether this list is read-only or not

toArray() method
public array toArray()
{return} array the list of items in array


CListIterator

All Packages | Methods
Package | system.collections
Inheritance | class CListIterator
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CListIterator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CListIterator implements an interator for CList.

It allows CList to return a new iterator for traversing the items in the list.

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CListIterator
current() | Returns the current array item. | CListIterator
key() | Returns the key of the current array item. | CListIterator
next() | Moves the internal pointer to the next array item. | CListIterator
rewind() | Rewinds internal array pointer. | CListIterator
valid() | Returns whether there is an item at current position. | CListIterator

Method Details

__construct() method
public void __construct(array $data)
$data array the data to be iterated through

Constructor.

current() method
public mixed current()
{return} mixed the current array item

Returns the current array item. This method is required by the interface Iterator.

key() method
public integer key()
{return} integer the key of the current array item

Returns the key of the current array item. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next array item. This method is required by the interface Iterator.

rewind() method
public void rewind()

Rewinds internal array pointer. This method is required by the interface Iterator.

valid() method
public boolean valid()
{return} boolean

Returns whether there is an item at current position. This method is required by the interface Iterator.


CMap

Package | system.collections
Inheritance | class CMap » CComponent
Implements | IteratorAggregate, Traversable, ArrayAccess, Countable
Subclasses | CAttributeCollection, CConfiguration, CCookieCollection, CFormElementCollection
Since | 1.0
Version | $Id: CMap.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMap implements a collection that takes key-value pairs.

You can access, add or remove an item with a key by using itemAt, add, and remove. To get the number of the items in the map, use getCount. CMap can also be used like a regular array as follows,
$map[$key]=$value; // add a key-value pair
unset($map[$key]); // remove the value with the specified key
if(isset($map[$key])) // if the map contains the key
foreach($map as $key=>$value) // traverse the items in the map
$n=count($map);  // returns the number of items in the map

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the map | CMap
iterator | CMapIterator | Returns an iterator for traversing the items in the list. | CMap
keys | array | the key list | CMap
readOnly | boolean | whether this map is read-only or not. | CMap

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CMap
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds an item into the map. | CMap
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the map. | CMap
contains() |  | CMap
copyFrom() | Copies iterable data into the map. | CMap
count() | Returns the number of items in the map. | CMap
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CMap
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CMap
getKeys() |  | CMap
getReadOnly() |  | CMap
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
itemAt() | Returns the item with the specified key. | CMap
mergeArray() | Merges two arrays into one recursively. | CMap
mergeWith() | Merges iterable data into the map. | CMap
offsetExists() | Returns whether there is an element at the specified offset. | CMap
offsetGet() | Returns the element at the specified offset. | CMap
offsetSet() | Sets the element at the specified offset. | CMap
offsetUnset() | Unsets the element at the specified offset. | CMap
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the map by its key. | CMap
toArray() |  | CMap

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CMap

Property Details

count property read-only
public integer getCount()

the number of items in the map

iterator property read-only
public CMapIterator getIterator()

Returns an iterator for traversing the items in the list. This method is required by the interface IteratorAggregate.

keys property read-only
public array getKeys()

the key list

readOnly property
public boolean getReadOnly()
protected void setReadOnly(boolean $value)

whether this map is read-only or not. Defaults to false.

Method Details

__construct() method
public void __construct(array $data=NULL, boolean $readOnly=false)
$data | array | the intial data. Default is null, meaning no initialization.
$readOnly | boolean | whether the list is read-only

Constructor. Initializes the list with an array or an iterable object.

add() method
public void add(mixed $key, mixed $value)
$key | mixed | key
$value | mixed | value

Adds an item into the map. Note, if the specified key already exists, the old value will be overwritten.

clear() method
public void clear()

Removes all items in the map.

contains() method
public boolean contains(mixed $key)
$key | mixed | the key
{return} | boolean | whether the map contains an item with the specified key

copyFrom() method
public void copyFrom(mixed $data)
$data mixed the data to be copied from, must be an array or object implementing Traversable

Copies iterable data into the map. Note, existing data in the map will be cleared first.

count() method
public integer count()
{return} integer number of items in the map.

Returns the number of items in the map. This method is required by Countable interface.

getCount() method
public integer getCount()
{return} integer the number of items in the map

getIterator() method
public CMapIterator getIterator()
{return} CMapIterator an iterator for traversing the items in the list.

Returns an iterator for traversing the items in the list. This method is required by the interface IteratorAggregate.

getKeys() method
public array getKeys()
{return} array the key list

getReadOnly() method
public boolean getReadOnly()
{return} boolean whether this map is read-only or not. Defaults to false.

itemAt() method
public mixed itemAt(mixed $key)
$key | mixed | the key
{return} | mixed | the element at the offset, null if no element is found at the offset

Returns the item with the specified key. This method is exactly the same as offsetGet.

mergeArray() method
public static array mergeArray(array $a, array $b)
$a | array | array to be merged to
$b | array | array to be merged from
{return} | array | the merged array (the original arrays are not changed.)

Merges two arrays into one recursively.

See Also

  • mergeWith
mergeWith() method
public void mergeWith(mixed $data, boolean $recursive=true)
$data | mixed | the data to be merged with, must be an array or object implementing Traversable
$recursive | boolean | whether the merging should be recursive.

Merges iterable data into the map.

Existing elements in the map will be overwritten if their keys are the same as those in the source. If the merge is recursive, the following algorithm is performed:

  • the map data is saved as $a, and the source data is saved as $b;
  • if $a and $b both have an array indxed at the same string key, the arrays will be merged using this algorithm;
  • any integer-indexed elements in $b will be appended to $a and reindxed accordingly;
  • any string-indexed elements in $b will overwrite elements in $a with the same index;

offsetExists() method
public boolean offsetExists(mixed $offset)
$offset | mixed | the offset to check on
{return} | boolean |

Returns whether there is an element at the specified offset. This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(integer $offset)
$offset | integer | the offset to retrieve element.
{return} | mixed | the element at the offset, null if no element is found at the offset

Returns the element at the specified offset. This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(integer $offset, mixed $item)
$offset | integer | the offset to set element
$item | mixed | the element value

Sets the element at the specified offset. This method is required by the interface ArrayAccess.

offsetUnset() method
public void offsetUnset(mixed $offset)
$offset mixed the offset to unset element

Unsets the element at the specified offset. This method is required by the interface ArrayAccess.

remove() method
public mixed remove(mixed $key)
$key | mixed | the key of the item to be removed
{return} | mixed | the removed value, null if no such key exists.

Removes an item from the map by its key.

setReadOnly() method
protected void setReadOnly(boolean $value)
$value boolean whether this list is read-only or not

toArray() method
public array toArray()
{return} array the list of items in array


CMapIterator

All Packages | Methods
Package | system.collections
Inheritance | class CMapIterator
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CMapIterator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMapIterator implements an interator for CMap.

It allows CMap to return a new iterator for traversing the items in the map.

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CMapIterator
current() | Returns the current array element. | CMapIterator
key() | Returns the key of the current array element. | CMapIterator
next() | Moves the internal pointer to the next array element. | CMapIterator
rewind() | Rewinds internal array pointer. | CMapIterator
valid() | Returns whether there is an element at current position. | CMapIterator

Method Details

__construct() method
public void __construct(array $data)
$data array the data to be iterated through

Constructor.

current() method
public mixed current()
{return} mixed the current array element

Returns the current array element. This method is required by the interface Iterator.

key() method
public mixed key()
{return} mixed the key of the current array element

Returns the key of the current array element. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next array element. This method is required by the interface Iterator.

rewind() method
public void rewind()

Rewinds internal array pointer. This method is required by the interface Iterator.

valid() method
public boolean valid()
{return} boolean

Returns whether there is an element at current position. This method is required by the interface Iterator.


CQueue

Package | system.collections
Inheritance | class CQueue » CComponent
Implements | IteratorAggregate, Traversable, Countable
Since | 1.0
Version | $Id: CQueue.php 1678 2010-01-07 21:02:00Z qiang.xue $
CQueue implements a queue.

The typical queue operations are implemented, which include enqueue(), dequeue() and peek(). In addition, contains() can be used to check if an item is contained in the queue. To obtain the number of the items in the queue, check the Count property.

Items in the queue may be traversed using foreach as follows,
foreach($queue as $item) ...

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the queue | CQueue
iterator | Iterator | Returns an iterator for traversing the items in the queue. | CQueue

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CQueue
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the queue. | CQueue
contains() |  | CQueue
copyFrom() | Copies iterable data into the queue. | CQueue
count() | Returns the number of items in the queue. | CQueue
dequeue() | Removes and returns the object at the beginning of the queue. | CQueue
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
enqueue() | Adds an object to the end of the queue. | CQueue
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CQueue
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the queue. | CQueue
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
peek() | Returns the item at the top of the queue. | CQueue
raiseEvent() | Raises an event. | CComponent
toArray() |  | CQueue

Property Details

count property read-only
public integer getCount()

the number of items in the queue

iterator property read-only
public Iterator getIterator()

Returns an iterator for traversing the items in the queue. This method is required by the interface IteratorAggregate.

Method Details

__construct() method
public void __construct(array $data=NULL)
$data array the intial data. Default is null, meaning no initialization.

Constructor. Initializes the queue with an array or an iterable object.

clear() method
public void clear()

Removes all items in the queue.

contains() method
public boolean contains(mixed $item)
$item | mixed | the item
{return} | boolean | whether the queue contains the item

copyFrom() method
public void copyFrom(mixed $data)
$data mixed the data to be copied from, must be an array or object implementing Traversable

Copies iterable data into the queue. Note, existing data in the list will be cleared first.

count() method
public integer count()
{return} integer number of items in the queue.

Returns the number of items in the queue. This method is required by Countable interface.

dequeue() method
public mixed dequeue()
{return} mixed the item at the beginning of the queue

Removes and returns the object at the beginning of the queue.

enqueue() method
public void enqueue(mixed $item)
$item mixed the item to be appended into the queue

Adds an object to the end of the queue.

getCount() method
public integer getCount()
{return} integer the number of items in the queue

getIterator() method
public Iterator getIterator()
{return} Iterator an iterator for traversing the items in the queue.

Returns an iterator for traversing the items in the queue. This method is required by the interface IteratorAggregate.

peek() method
public mixed peek()
{return} mixed item at the top of the queue

Returns the item at the top of the queue.

toArray() method
public array toArray()
{return} array the list of items in queue


CQueueIterator

All Packages | Methods
Package | system.collections
Inheritance | class CQueueIterator
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CQueueIterator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CQueueIterator implements an interator for CQueue.

It allows CQueue to return a new iterator for traversing the items in the queue.

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CQueueIterator
current() | Returns the current array item. | CQueueIterator
key() | Returns the key of the current array item. | CQueueIterator
next() | Moves the internal pointer to the next array item. | CQueueIterator
rewind() | Rewinds internal array pointer. | CQueueIterator
valid() | Returns whether there is an item at current position. | CQueueIterator

Method Details

__construct() method
public void __construct(array $data)
$data array the data to be iterated through

Constructor.

current() method
public mixed current()
{return} mixed the current array item

Returns the current array item. This method is required by the interface Iterator.

key() method
public integer key()
{return} integer the key of the current array item

Returns the key of the current array item. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next array item. This method is required by the interface Iterator.

rewind() method
public void rewind()

Rewinds internal array pointer. This method is required by the interface Iterator.

valid() method
public boolean valid()
{return} boolean

Returns whether there is an item at current position. This method is required by the interface Iterator.


CStack

Package | system.collections
Inheritance | class CStack » CComponent
Implements | IteratorAggregate, Traversable, Countable
Since | 1.0
Version | $Id: CStack.php 1678 2010-01-07 21:02:00Z qiang.xue $
CStack implements a stack.

The typical stack operations are implemented, which include push(), pop() and peek(). In addition, contains() can be used to check if an item is contained in the stack. To obtain the number of the items in the stack, check the Count property.

Items in the stack may be traversed using foreach as follows,
foreach($stack as $item) ...

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the stack | CStack
iterator | Iterator | Returns an iterator for traversing the items in the stack. | CStack

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CStack
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the stack. | CStack
contains() |  | CStack
copyFrom() | Copies iterable data into the stack. | CStack
count() | Returns the number of items in the stack. | CStack
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CStack
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the stack. | CStack
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
peek() | Returns the item at the top of the stack. | CStack
pop() | Pops up the item at the top of the stack. | CStack
push() | Pushes an item into the stack. | CStack
raiseEvent() | Raises an event. | CComponent
toArray() |  | CStack

Property Details

count property read-only
public integer getCount()

the number of items in the stack

iterator property read-only
public Iterator getIterator()

Returns an iterator for traversing the items in the stack. This method is required by the interface IteratorAggregate.

Method Details

__construct() method
public void __construct(array $data=NULL)
$data array the initial data. Default is null, meaning no initialization.

Constructor. Initializes the stack with an array or an iterable object.

clear() method
public void clear()

Removes all items in the stack.

contains() method
public boolean contains(mixed $item)
$item | mixed | the item
{return} | boolean | whether the stack contains the item

copyFrom() method
public void copyFrom(mixed $data)
$data mixed the data to be copied from, must be an array or object implementing Traversable

Copies iterable data into the stack. Note, existing data in the list will be cleared first.

count() method
public integer count()
{return} integer number of items in the stack.

Returns the number of items in the stack. This method is required by Countable interface.

getCount() method
public integer getCount()
{return} integer the number of items in the stack

getIterator() method
public Iterator getIterator()
{return} Iterator an iterator for traversing the items in the stack.

Returns an iterator for traversing the items in the stack. This method is required by the interface IteratorAggregate.

peek() method
public mixed peek()
{return} mixed item at the top of the stack

Returns the item at the top of the stack. Unlike pop(), this method does not remove the item from the stack.

pop() method
public mixed pop()
{return} mixed the item at the top of the stack

Pops up the item at the top of the stack.

push() method
public void push(mixed $item)
$item mixed the item to be pushed into the stack

Pushes an item into the stack.

toArray() method
public array toArray()
{return} array the list of items in stack


CStackIterator

All Packages | Methods
Package | system.collections
Inheritance | class CStackIterator
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CStackIterator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CStackIterator implements an interator for CStack.

It allows CStack to return a new iterator for traversing the items in the stack.

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CStackIterator
current() | Returns the current array item. | CStackIterator
key() | Returns the key of the current array item. | CStackIterator
next() | Moves the internal pointer to the next array item. | CStackIterator
rewind() | Rewinds internal array pointer. | CStackIterator
valid() | Returns whether there is an item at current position. | CStackIterator

Method Details

__construct() method
public void __construct(array $data)
$data array the data to be iterated through

Constructor.

current() method
public mixed current()
{return} mixed the current array item

Returns the current array item. This method is required by the interface Iterator.

key() method
public integer key()
{return} integer the key of the current array item

Returns the key of the current array item. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next array item. This method is required by the interface Iterator.

rewind() method
public void rewind()

Rewinds internal array pointer. This method is required by the interface Iterator.

valid() method
public boolean valid()
{return} boolean

Returns whether there is an item at current position. This method is required by the interface Iterator.


CTypedList

Package | system.collections
Inheritance | class CTypedList » CList » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CTypedList.php 1678 2010-01-07 21:02:00Z qiang.xue $
CTypedList represents a list whose items are of the certain type.

CTypedList extends CList by making sure that the elements to be added to the list is of certain class type.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the list | CList
iterator | Iterator | Returns an iterator for traversing the items in the list. | CList
readOnly | boolean | whether this list is read-only or not. | CList

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CTypedList
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Appends an item at the end of the list. | CList
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the list. | CList
contains() |  | CList
copyFrom() | Copies iterable data into the list. | CList
count() | Returns the number of items in the list. | CList
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CList
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CList
getReadOnly() |  | CList
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
indexOf() |  | CList
insertAt() | Inserts an item at the specified position. | CTypedList
itemAt() | Returns the item at the specified offset. | CList
mergeWith() | Merges iterable data into the map. | CList
offsetExists() | Returns whether there is an item at the specified offset. | CList
offsetGet() | Returns the item at the specified offset. | CList
offsetSet() | Sets the item at the specified offset. | CList
offsetUnset() | Unsets the item at the specified offset. | CList
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the list. | CList
removeAt() | Removes an item at the specified position. | CList
toArray() |  | CList

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CList

Method Details

__construct() method
public void __construct(string $type)
$type string class type

Constructor.

insertAt() method
public void insertAt(integer $index, mixed $item)
$index | integer | the specified position.
$item | mixed | new item

Inserts an item at the specified position. This method overrides the parent implementation by checking the item to be inserted is of certain type.


CConsoleApplication

All Packages | Properties | Methods | Events
Package | system.console
Inheritance | class CConsoleApplication » CApplication » CModule » CComponent
Since | 1.0
Version | $Id: CConsoleApplication.php 1678 2010-01-07 21:02:00Z qiang.xue $
CConsoleApplication represents a console application.

CConsoleApplication extends CApplication by providing functionalities specific to console requests. In particular, it deals with console requests through a command-based approach:
  • A console application consists of one or several possible user commands;
  • Each user command is implemented as a class extending CConsoleCommand;
  • User specifies which command to run on the command line;
  • The command processes the user request with the specified parameters.

The command classes reside in the directory commandPath. The name of the class follows the pattern: <command-name>Command, and its file name is the same the class name. For example, the 'ShellCommand' class defines a 'shell' command and the class file name is 'ShellCommand.php'.

To run the console application, enter the following on the command line:
php path/to/entry_script.php  [param 1] [param 2] ...

You may use the following to see help instructions about a command:
php path/to/entry_script.php help

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the root directory of the application. | CApplication
behaviors | array | the behaviors that should be attached to the module. | CModule
cache | CCache | the cache application component. | CApplication
charset | string | the charset currently used for the application. | CApplication
commandMap | array | mapping from command name to command configurations. | CConsoleApplication
commandPath | string | the directory that contains the command classes. | CConsoleApplication
commandRunner | CConsoleCommandRunner | Returns the command runner. | CConsoleApplication
components | array | the currently loaded components (indexed by their IDs) | CModule
coreMessages | CPhpMessageSource | the core message translations | CApplication
dateFormatter | CDateFormatter | the locale-dependent date formatter. | CApplication
db | CDbConnection | the database connection | CApplication
errorHandler | CErrorHandler | the error handler application component. | CApplication
extensionPath | string | Returns the root directory that holds all third-party extensions. | CApplication
id | string | a unique identifier for the application. | CApplication
language | string | the language that the user is using and the application should be targeted to. | CApplication
locale | CLocale | the locale instance | CApplication
localeDataPath | string | the directory that contains the locale data. | CApplication
messages | CMessageSource | the application message translations | CApplication
modulePath | string | the directory that contains the application modules. | CModule
modules | array | the configuration of the currently installed modules (module ID => configuration) | CModule
name | string | the application name. | CApplication
numberFormatter | CNumberFormatter | the locale-dependent number formatter. | CApplication
params | CAttributeCollection | the list of user-defined parameters | CModule
parentModule | CModule | the parent module. | CModule
preload | array | the IDs of the application components that should be preloaded. | CModule
request | CHttpRequest | the request component | CApplication
runtimePath | string | the directory that stores runtime files. | CApplication
securityManager | CSecurityManager | the security manager application component. | CApplication
sourceLanguage | string | the language that the application is written in. | CApplication
statePersister | CStatePersister | the state persister application component. | CApplication
timeZone | string | Returns the time zone used by this application. | CApplication
urlManager | CUrlManager | the URL manager component | CApplication

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CApplication
__get() | Getter magic method. | CModule
__isset() | Checks if a property value is null. | CModule
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearGlobalState() | Clears a global value. | CApplication
configure() | Configures the module with the specified configuration. | CModule
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
displayError() | Displays the captured PHP error. | CConsoleApplication
displayException() | Displays the uncaught PHP exception. | CConsoleApplication
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
end() | Terminates the application. | CApplication
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
findLocalizedFile() | Returns the localized version of a specified file. | CApplication
getBasePath() |  | CApplication
getCache() |  | CApplication
getCommandPath() |  | CConsoleApplication
getCommandRunner() | Returns the command runner. | CConsoleApplication
getComponent() | Retrieves the named application component. | CModule
getComponents() |  | CModule
getCoreMessages() |  | CApplication
getDateFormatter() |  | CApplication
getDb() |  | CApplication
getErrorHandler() |  | CApplication
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getExtensionPath() | Returns the root directory that holds all third-party extensions. | CApplication
getGlobalState() | Returns a global value. | CApplication
getId() |  | CApplication
getLanguage() |  | CApplication
getLocale() |  | CApplication
getLocaleDataPath() |  | CApplication
getMessages() |  | CApplication
getModule() | Retrieves the named application module. | CModule
getModulePath() |  | CModule
getModules() |  | CModule
getNumberFormatter() |  | CApplication
getParams() |  | CModule
getParentModule() |  | CModule
getRequest() |  | CApplication
getRuntimePath() |  | CApplication
getSecurityManager() |  | CApplication
getStatePersister() |  | CApplication
getTimeZone() | Returns the time zone used by this application. | CApplication
getUrlManager() |  | CApplication
handleError() | Handles PHP execution errors such as warnings, notices. | CApplication
handleException() | Handles uncaught PHP exceptions. | CApplication
hasComponent() |  | CModule
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
onBeginRequest() | Raised right BEFORE the application processes the request. | CApplication
onEndRequest() | Raised right AFTER the application processes the request. | CApplication
onError() | Raised when a PHP execution error occurs. | CApplication
onException() | Raised when an uncaught PHP exception occurs. | CApplication
processRequest() | Processes the user request. | CConsoleApplication
raiseEvent() | Raises an event. | CComponent
run() | Runs the application. | CApplication
setAliases() | Defines the root aliases. | CModule
setBasePath() | Sets the root directory of the application. | CApplication
setCommandPath() |  | CConsoleApplication
setComponent() | Puts a component under the management of the module. | CModule
setComponents() | Sets the application components. | CModule
setExtensionPath() |  | CApplication
setGlobalState() | Sets a global value. | CApplication
setId() |  | CApplication
setImport() | Sets the aliases that are used in the module. | CModule
setLanguage() | Specifies which language the application is targeted to. | CApplication
setLocaleDataPath() |  | CApplication
setModulePath() |  | CModule
setModules() | Configures the sub-modules of this module. | CModule
setParams() |  | CModule
setRuntimePath() |  | CApplication
setTimeZone() | Sets the time zone used by this application. | CApplication

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCommandRunner() | Creates the command runner instance. | CConsoleApplication
init() | Initializes the application by creating the command runner. | CConsoleApplication
initSystemHandlers() | Initializes the class autoloader and error handlers. | CApplication
loadGlobalState() | Loads the global state data from persistent storage. | CApplication
preinit() | Preinitializes the module. | CModule
preloadComponents() | Loads static application components. | CModule
registerCoreComponents() | Registers the core application components. | CApplication
saveGlobalState() | Saves the global state data into persistent storage. | CApplication

Events

Hide inherited events

Event | Description | Defined By
onBeginRequest | Raised right BEFORE the application processes the request. | CApplication
onEndRequest | Raised right AFTER the application processes the request. | CApplication
onException | Raised when an uncaught PHP exception occurs. | CApplication
onError | Raised when a PHP execution error occurs. | CApplication

Property Details

commandMap property
public array $commandMap;

mapping from command name to command configurations. Each command configuration can be either a string or an array. If the former, the string should be the file path of the command class. If the latter, the array must contain a 'class' element which specifies the command's class name or class path alias. The rest name-value pairs in the array are used to initialize the corresponding command properties. For example,

array(
  'email'=>array(
     'class'=>'path.to.Mailer',
     'interval'=>3600,
  ),
  'log'=>'path/to/LoggerCommand.php',
)

commandPath property
public string getCommandPath()
public void setCommandPath(string $value)

the directory that contains the command classes. Defaults to 'protected/commands'.

commandRunner property read-only
public CConsoleCommandRunner getCommandRunner()

Returns the command runner.

Method Details

createCommandRunner() method
protected CConsoleCommandRunner createCommandRunner()
{return} CConsoleCommandRunner the command runner

Creates the command runner instance.

displayError() method
public void displayError(integer $code, string $message, string $file, string $line)
$code | integer | error code
$message | string | error message
$file | string | error file
$line | string | error line

Displays the captured PHP error. This method displays the error in console mode when there is no active error handler.

displayException() method
public void displayException(Exception $exception)
$exception Exception the uncaught exception

Displays the uncaught PHP exception. This method displays the exception in console mode when there is no active error handler.

getCommandPath() method
public string getCommandPath()
{return} string the directory that contains the command classes. Defaults to 'protected/commands'.

getCommandRunner() method
public CConsoleCommandRunner getCommandRunner()
{return} CConsoleCommandRunner the command runner.

Returns the command runner.

init() method
protected void init()

Initializes the application by creating the command runner.

processRequest() method
public void processRequest()

Processes the user request. This method creates a console command runner to handle the particular user command.

setCommandPath() method
public void setCommandPath(string $value)
$value string the directory that contains the command classes.


CConsoleCommand

Package | system.console
Inheritance | abstract class CConsoleCommand » CComponent
Subclasses | CHelpCommand
Since | 1.0
Version | $Id: CConsoleCommand.php 1832 2010-02-20 03:22:45Z qiang.xue $
CConsoleCommand represents an executable user command.

The run method must be implemented with the actual command execution logic. You may override getHelp to provide more detailed description of the command.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandRunner | CConsoleCommandRunner | the command runner instance | CConsoleCommand
help | string | Provides the command description. | CConsoleCommand
name | string | the command name. | CConsoleCommand

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CConsoleCommand
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
buildFileList() | Builds the file list of a directory. | CConsoleCommand
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
copyFiles() | Copies a list of files from one place to another. | CConsoleCommand
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
ensureDirectory() | Creates all parent directories if they do not exist. | CConsoleCommand
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandRunner() |  | CConsoleCommand
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHelp() | Provides the command description. | CConsoleCommand
getName() |  | CConsoleCommand
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
pluralize() | Converts a word to its plural form. | CConsoleCommand
raiseEvent() | Raises an event. | CComponent
renderFile() | Renders a view file. | CConsoleCommand
run() | Executes the command. | CConsoleCommand
usageError() | Displays a usage error. | CConsoleCommand

Property Details

commandRunner property read-only
public CConsoleCommandRunner getCommandRunner()

the command runner instance

help property read-only
public string getHelp()

Provides the command description. This method may be overridden to return the actual command description.

name property read-only
public string getName()

the command name.

Method Details

__construct() method
public void __construct(string $name, CConsoleCommandRunner $runner)
$name | string | name of the command
$runner | CConsoleCommandRunner | the command runner

Constructor.

buildFileList() method
public array buildFileList(string $sourceDir, string $targetDir, string $baseDir='')
$sourceDir | string | the source directory
$targetDir | string | the target directory
$baseDir | string | base directory
{return} | array | the file list (see copyFiles)

Builds the file list of a directory. This method traverses through the specified directory and builds a list of files and subdirectories that the directory contains. The result of this function can be passed to copyFiles.

copyFiles() method
public void copyFiles(array $fileList)
$fileList array the list of files to be copied (name=>spec). The array keys are names displayed during the copy process, and array values are specifications for files to be copied. Each array value must be an array of the following structure:
  • source: required, the full path of the file/directory to be copied from
  • target: required, the full path of the file/directory to be copied to
  • callback: optional, the callback to be invoked when copying a file. The callback function should be declared as follows:
      function foo($source,$params)
    where $source parameter is the source file path, and the content returned by the function will be saved into the target file.
  • params: optional, the parameters to be passed to the callback

Copies a list of files from one place to another.

See Also

  • buildFileList
ensureDirectory() method
public void ensureDirectory(string $directory)
$directory string the directory to be checked

Creates all parent directories if they do not exist.

getCommandRunner() method
public CConsoleCommandRunner getCommandRunner()
{return} CConsoleCommandRunner the command runner instance

getHelp() method
public string getHelp()
{return} string the command description. Defaults to 'Usage: php entry-script.php command-name'.

Provides the command description. This method may be overridden to return the actual command description.

getName() method
public string getName()
{return} string the command name.

pluralize() method
public string pluralize(string $name)
$name | string | the word to be pluralized
{return} | string | the pluralized word

Converts a word to its plural form.

renderFile() method
public mixed renderFile(string $_viewFile_, array $_data_=NULL, boolean $_return_=false)
$_viewFile_ | string | view file path
$_data_ | array | optional data to be extracted as local view variables
$_return_ | boolean | whether to return the rendering result instead of displaying it
{return} | mixed | the rendering result if required. Null otherwise.

Renders a view file.

run() method
abstract public void run(array $args)
$args array command line parameters for this command.

Executes the command.

usageError() method
public void usageError(string $message)
$message string the error message

Displays a usage error. This method will then terminate the execution of the current application.


CConsoleCommandRunner

Package | system.console
Inheritance | class CConsoleCommandRunner » CComponent
Since | 1.0
Version | $Id: CConsoleCommandRunner.php 1832 2010-02-20 03:22:45Z qiang.xue $
CConsoleCommandRunner manages commands and executes the requested command.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commands | array | list of all available commands (command name=>command configuration). | CConsoleCommandRunner
scriptName | string | the entry script name | CConsoleCommandRunner

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addCommands() | Adds commands from the specified command path. | CConsoleCommandRunner
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createCommand() |  | CConsoleCommandRunner
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
findCommands() | Searches for commands under the specified directory. | CConsoleCommandRunner
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getScriptName() |  | CConsoleCommandRunner
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
run() | Executes the requested command. | CConsoleCommandRunner

Property Details

commands property
public array $commands;

list of all available commands (command name=>command configuration). Each command configuration can be either a string or an array. If the former, the string should be the class name or class path alias of the command. If the latter, the array must contain a 'class' element which specifies the command's class name or class path alias. The rest name-value pairs in the array are used to initialize the corresponding command properties. For example,

array(
  'email'=>array(
     'class'=>'path.to.Mailer',
     'interval'=>3600,
  ),
  'log'=>'path.to.LoggerCommand',
)

scriptName property read-only
public string getScriptName()

the entry script name

Method Details

addCommands() method
public void addCommands(string $path)
$path string the alias of the directory containing the command class files.

Adds commands from the specified command path. If a command already exists, the new one will be ignored.

createCommand() method
public CConsoleCommand createCommand(string $name)
$name | string | command name (case-insensitive)
{return} | CConsoleCommand | the command object. Null if the name is invalid.

findCommands() method
public array findCommands(string $path)
$path | string | the directory containing the command class files.
{return} | array | list of commands (command name=>command class file)

Searches for commands under the specified directory.

getScriptName() method
public string getScriptName()
{return} string the entry script name

run() method
public void run(array $args)
$args array list of user supplied parameters (including the entry script name and the command name).

Executes the requested command.


CHelpCommand

Package | system.console
Inheritance | class CHelpCommand » CConsoleCommand » CComponent
Since | 1.0
Version | $Id: CHelpCommand.php 1678 2010-01-07 21:02:00Z qiang.xue $
CHelpCommand represents a console help command.

CHelpCommand displays the available command list or the help instructions about a specific command.

To use this command, enter the following on the command line:
php path/to/entry_script.php help [command name]
In the above, if the command name is not provided, it will display all available commands.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandRunner | CConsoleCommandRunner | the command runner instance | CConsoleCommand
help | string | Provides the command description. | CHelpCommand
name | string | the command name. | CConsoleCommand

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CConsoleCommand
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
buildFileList() | Builds the file list of a directory. | CConsoleCommand
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
copyFiles() | Copies a list of files from one place to another. | CConsoleCommand
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
ensureDirectory() | Creates all parent directories if they do not exist. | CConsoleCommand
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandRunner() |  | CConsoleCommand
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHelp() | Provides the command description. | CHelpCommand
getName() |  | CConsoleCommand
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
pluralize() | Converts a word to its plural form. | CConsoleCommand
raiseEvent() | Raises an event. | CComponent
renderFile() | Renders a view file. | CConsoleCommand
run() | Execute the action. | CHelpCommand
usageError() | Displays a usage error. | CConsoleCommand

Property Details

help property read-only
public string getHelp()

Provides the command description.

Method Details

getHelp() method
public string getHelp()
{return} string the command description.

Provides the command description.

run() method
public void run(array $args)
$args array command line parameters specific for this command

Execute the action.


CDbCommand

Package | system.db
Inheritance | class CDbCommand » CComponent
Since | 1.0
Version | $Id: CDbCommand.php 1880 2010-03-10 21:48:45Z qiang.xue $
CDbCommand represents an SQL statement to execute against a database.

It is usually created by calling CDbConnection::createCommand. The SQL statement to be executed may be set via Text.

To execute a non-query SQL (such as insert, delete, update), call execute. To execute an SQL statement that returns result data set (such as SELECT), use query or its convenient versions queryRow, queryColumn, or queryScalar.

If an SQL statement returns results (such as a SELECT SQL), the results can be accessed via the returned CDbDataReader.

CDbCommand supports SQL statment preparation and parameter binding. Call bindParam to bind a PHP variable to a parameter in SQL. Call bindValue to bind a value to an SQL parameter. When binding a parameter, the SQL statement is automatically prepared. You may also call prepare to explicitly prepare an SQL statement.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
connection | CDbConnection | the connection associated with this command | CDbCommand
pdoStatement | PDOStatement | the underlying PDOStatement for this command It could be null if the statement is not prepared yet. | CDbCommand
text | string | the SQL statement to be executed | CDbCommand

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbCommand
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__sleep() | Set the statement to null when serializing. | CDbCommand
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindParam() | Binds a parameter to the SQL statement to be executed. | CDbCommand
bindValue() | Binds a value to a parameter. | CDbCommand
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
cancel() | Cancels the execution of the SQL statement. | CDbCommand
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
execute() | Executes the SQL statement. | CDbCommand
getConnection() |  | CDbCommand
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getPdoStatement() |  | CDbCommand
getText() |  | CDbCommand
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
prepare() | Prepares the SQL statement to be executed. | CDbCommand
query() | Executes the SQL statement and returns query result. | CDbCommand
queryAll() | Executes the SQL statement and returns all rows. | CDbCommand
queryColumn() | Executes the SQL statement and returns the first column of the result. | CDbCommand
queryRow() | Executes the SQL statement and returns the first row of the result. | CDbCommand
queryScalar() | Executes the SQL statement and returns the value of the first column in the first row of data. | CDbCommand
raiseEvent() | Raises an event. | CComponent
setText() | Specifies the SQL statement to be executed. | CDbCommand

Property Details

connection property read-only
public CDbConnection getConnection()

the connection associated with this command

pdoStatement property read-only
public PDOStatement getPdoStatement()

the underlying PDOStatement for this command It could be null if the statement is not prepared yet.

text property
public string getText()
public void setText(string $value)

the SQL statement to be executed

Method Details

__construct() method
public void __construct(CDbConnection $connection, string $text)
$connection | CDbConnection | the database connection
$text | string | the SQL statement to be executed

Constructor.

__sleep() method
public void __sleep()

Set the statement to null when serializing.

bindParam() method
public CDbCommand bindParam(mixed $name, mixed $value, int $dataType=NULL, int $length=NULL)
$name | mixed | Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
$value | mixed | Name of the PHP variable to bind to the SQL statement parameter
$dataType | int | SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
$length | int | length of the data type
{return} | CDbCommand | the current command being executed (this is available since version 1.0.8)

Binds a parameter to the SQL statement to be executed.

See Also

  • http://www.php.net/manual/en/function.PDOStatement-bindParam.php
bindValue() method
public CDbCommand bindValue(mixed $name, mixed $value, int $dataType=NULL)
$name | mixed | Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
$value | mixed | The value to bind to the parameter
$dataType | int | SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
{return} | CDbCommand | the current command being executed (this is available since version 1.0.8)

Binds a value to a parameter.

See Also

  • http://www.php.net/manual/en/function.PDOStatement-bindValue.php
cancel() method
public void cancel()

Cancels the execution of the SQL statement.

execute() method
public integer execute(array $params=array ( ))
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | integer | number of rows affected by the execution.

Executes the SQL statement. This method is meant only for executing non-query SQL statement. No result set will be returned.

getConnection() method
public CDbConnection getConnection()
{return} CDbConnection the connection associated with this command

getPdoStatement() method
public PDOStatement getPdoStatement()
{return} PDOStatement the underlying PDOStatement for this command It could be null if the statement is not prepared yet.

getText() method
public string getText()
{return} string the SQL statement to be executed

prepare() method
public void prepare()

Prepares the SQL statement to be executed. For complex SQL statement that is to be executed multiple times, this may improve performance. For SQL statement with binding parameters, this method is invoked automatically.

query() method
public CDbDataReader query(array $params=array ( ))
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | CDbDataReader | the reader object for fetching the query result

Executes the SQL statement and returns query result. This method is for executing an SQL query that returns result set.

queryAll() method
public array queryAll(boolean $fetchAssociative=true, array $params=array ( ))
$fetchAssociative | boolean | whether each row should be returned as an associated array with column names as the keys or the array keys are column indexes (0-based).
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | array | all rows of the query result. Each array element is an array representing a row. An empty array is returned if the query results in nothing.

Executes the SQL statement and returns all rows.

queryColumn() method
public array queryColumn(array $params=array ( ))
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | array | the first column of the query result. Empty array if no result.

Executes the SQL statement and returns the first column of the result. This is a convenient method of query when only the first column of data is needed. Note, the column returned will contain the first element in each row of result.

queryRow() method
public array queryRow(boolean $fetchAssociative=true, array $params=array ( ))
$fetchAssociative | boolean | whether the row should be returned as an associated array with column names as the keys or the array keys are column indexes (0-based).
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | array | the first row of the query result, false if no result.

Executes the SQL statement and returns the first row of the result. This is a convenient method of query when only the first row of data is needed.

queryScalar() method
public mixed queryScalar(array $params=array ( ))
$params | array | input parameters (name=>value) for the SQL execution. This is an alternative to bindParam and bindValue. If you have multiple input parameters, passing them in this way can improve the performance. Note that you pass parameters in this way, you cannot bind parameters or values using bindParam or bindValue, and vice versa. binding methods and the input parameters this way can improve the performance. This parameter has been available since version 1.0.10.
{return} | mixed | the value of the first column in the first row of the query result. False is returned if there is no value.

Executes the SQL statement and returns the value of the first column in the first row of data. This is a convenient method of query when only a single scalar value is needed (e.g. obtaining the count of the records).

setText() method
public void setText(string $value)
$value string the SQL statement to be executed

Specifies the SQL statement to be executed. Any previous execution will be terminated or cancel.


CDbConnection

Package | system.db
Inheritance | class CDbConnection » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CDbConnection.php 1848 2010-02-27 05:41:52Z qiang.xue $
CDbConnection represents a connection to a database.

CDbConnection works together with CDbCommand, CDbDataReader and CDbTransaction to provide data access to various DBMS in a common set of APIs. They are a thin wrapper of the PDO PHP extension.

To establish a connection, set active to true after specifying connectionString, username and password.

The following example shows how to create a CDbConnection instance and establish the actual connection:
$connection=new CDbConnection($dsn,$username,$password);
$connection->active=true;

After the DB connection is established, one can execute an SQL statement like the following:
$command=$connection->createCommand($sqlStatement);
$command->execute();   // a non-query SQL statement execution
// or execute an SQL query and fetch the result set
$reader=$command->query();

// each $row is an array representing a row of data
foreach($reader as $row) ...

One can do prepared SQL execution and bind parameters to the prepared SQL:
$command=$connection->createCommand($sqlStatement);
$command->bindParam($name1,$value1);
$command->bindParam($name2,$value2);
$command->execute();

To use transaction, do like the following:
$transaction=$connection->beginTransaction();
try
{
   $connection->createCommand($sql1)->execute();
   $connection->createCommand($sql2)->execute();
   //.... other SQL executions
   $transaction->commit();
}
catch(Exception $e)
{
   $transaction->rollBack();
}

CDbConnection also provides a set of methods to support setting and querying of certain DBMS attributes, such as nullConversion.

Since CDbConnection implements the interface IApplicationComponent, it can be used as an application component and be configured in application configuration, like the following,
array(
    'components'=>array(
        'db'=>array(
            'class'=>'CDbConnection',
            'connectionString'=>'sqlite:path/to/dbfile',
        ),
    ),
)

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
active | boolean | whether the DB connection is established | CDbConnection
autoCommit | boolean | whether creating or updating a DB record will be automatically committed. | CDbConnection
autoConnect | boolean | whether the database connection should be automatically established the component is being initialized. | CDbConnection
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
charset | string | the charset used for database connection. | CDbConnection
clientVersion | string | the version information of the DB driver | CDbConnection
columnCase | mixed | the case of the column names | CDbConnection
commandBuilder | CDbCommandBuilder | Returns the SQL command builder for the current DB connection. | CDbConnection
connectionStatus | string | the status of the connection Some DBMS (such as sqlite) may not support this feature. | CDbConnection
connectionString | string | The Data Source Name, or DSN, contains the information required to connect to the database. | CDbConnection
currentTransaction | CDbTransaction | the currently active transaction. | CDbConnection
driverName | string | name of the DB driver | CDbConnection
emulatePrepare | boolean | whether to turn on prepare emulation. | CDbConnection
enableParamLogging | boolean | whether to log the values that are bound to a prepare SQL statement. | CDbConnection
enableProfiling | boolean | whether to enable profiling the SQL statements being executed. | CDbConnection
initSQLs | array | list of SQL statements that should be executed right after the DB connection is established. | CDbConnection
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
lastInsertID | string | Returns the ID of the last inserted row or sequence value. | CDbConnection
nullConversion | mixed | how the null and empty strings are converted | CDbConnection
password | string | the password for establishing DB connection. | CDbConnection
pdoInstance | PDO | the PDO instance, null if the connection is not established yet | CDbConnection
persistent | boolean | whether the connection is persistent or not Some DBMS (such as sqlite) may not support this feature. | CDbConnection
prefetch | boolean | whether the connection performs data prefetching | CDbConnection
schema | CDbSchema | the database schema for the current connection | CDbConnection
schemaCacheID | string | the ID of the cache application component that is used to cache the table metadata. | CDbConnection
schemaCachingDuration | integer | number of seconds that table metadata can remain valid in cache. | CDbConnection
schemaCachingExclude | array | list of tables whose metadata should NOT be cached. | CDbConnection
serverInfo | string | the information of DBMS server | CDbConnection
serverVersion | string | the version information of DBMS server | CDbConnection
stats | array | Returns the statistical results of SQL executions. | CDbConnection
tablePrefix | string | the default prefix for table names. | CDbConnection
timeout | int | timeout settings for the connection | CDbConnection
username | string | the username for establishing DB connection. | CDbConnection

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbConnection
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__sleep() | Close the connection when serializing. | CDbConnection
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginTransaction() | Starts a transaction. | CDbConnection
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createCommand() | Creates a command for execution. | CDbConnection
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getActive() |  | CDbConnection
getAttribute() | Obtains a specific DB connection attribute information. | CDbConnection
getAutoCommit() |  | CDbConnection
getAvailableDrivers() |  | CDbConnection
getClientVersion() |  | CDbConnection
getColumnCase() |  | CDbConnection
getCommandBuilder() | Returns the SQL command builder for the current DB connection. | CDbConnection
getConnectionStatus() |  | CDbConnection
getCurrentTransaction() |  | CDbConnection
getDriverName() |  | CDbConnection
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getLastInsertID() | Returns the ID of the last inserted row or sequence value. | CDbConnection
getNullConversion() |  | CDbConnection
getPdoInstance() |  | CDbConnection
getPdoType() | Determines the PDO type for the specified PHP type. | CDbConnection
getPersistent() |  | CDbConnection
getPrefetch() |  | CDbConnection
getSchema() |  | CDbConnection
getServerInfo() |  | CDbConnection
getServerVersion() |  | CDbConnection
getStats() | Returns the statistical results of SQL executions. | CDbConnection
getTimeout() |  | CDbConnection
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the component. | CDbConnection
quoteColumnName() | Quotes a column name for use in a query. | CDbConnection
quoteTableName() | Quotes a table name for use in a query. | CDbConnection
quoteValue() | Quotes a string value for use in a query. | CDbConnection
raiseEvent() | Raises an event. | CComponent
setActive() | Open or close the DB connection. | CDbConnection
setAttribute() | Sets an attribute on the database connection. | CDbConnection
setAutoCommit() |  | CDbConnection
setColumnCase() |  | CDbConnection
setNullConversion() |  | CDbConnection
setPersistent() |  | CDbConnection

Protected Methods

Hide inherited methods

Method | Description | Defined By
close() | Closes the currently active DB connection. | CDbConnection
createPdoInstance() | Creates the PDO instance. | CDbConnection
initConnection() | Initializes the open db connection. | CDbConnection
open() | Opens DB connection if it is currently not | CDbConnection

Property Details

active property
public boolean getActive()
public void setActive(boolean $value)

whether the DB connection is established

autoCommit property
public boolean getAutoCommit()
public void setAutoCommit(boolean $value)

whether creating or updating a DB record will be automatically committed. Some DBMS (such as sqlite) may not support this feature.

autoConnect property
public boolean $autoConnect;

whether the database connection should be automatically established the component is being initialized. Defaults to true. Note, this property is only effective when the CDbConnection object is used as an application component.

charset property
public string $charset;

the charset used for database connection. The property is only used for MySQL and PostgreSQL databases. Defaults to null, meaning using default charset as specified by the database.

clientVersion property read-only
public string getClientVersion()

the version information of the DB driver

columnCase property
public mixed getColumnCase()
public void setColumnCase(mixed $value)

the case of the column names

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
commandBuilder property read-only (available since v1.0.4)
public CDbCommandBuilder getCommandBuilder()

Returns the SQL command builder for the current DB connection.

connectionStatus property read-only
public string getConnectionStatus()

the status of the connection Some DBMS (such as sqlite) may not support this feature.

connectionString property
public string $connectionString;

The Data Source Name, or DSN, contains the information required to connect to the database.

See Also

  • http://www.php.net/manual/en/function.PDO-construct.php
currentTransaction property read-only
public CDbTransaction getCurrentTransaction()

the currently active transaction. Null if no active transaction.

driverName property read-only
public string getDriverName()

name of the DB driver

emulatePrepare property
public boolean $emulatePrepare;

whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare support to bypass the buggy native prepare support. Note, this property is only effective for PHP 5.1.3 or above.

enableParamLogging property (available since v1.0.5)
public boolean $enableParamLogging;

whether to log the values that are bound to a prepare SQL statement. Defaults to false. During development, you may consider setting this property to true so that parameter values bound to SQL statements are logged for debugging purpose. You should be aware that logging parameter values could be expensive and have significant impact on the performance of your application.

enableProfiling property (available since v1.0.6)
public boolean $enableProfiling;

whether to enable profiling the SQL statements being executed. Defaults to false. This should be mainly enabled and used during development to find out the bottleneck of SQL executions.

initSQLs property (available since v1.1.1)
public array $initSQLs;

list of SQL statements that should be executed right after the DB connection is established.

lastInsertID property read-only
public string getLastInsertID(string $sequenceName='')

Returns the ID of the last inserted row or sequence value.

See Also

  • http://www.php.net/manual/en/function.PDO-lastInsertId.php
nullConversion property
public mixed getNullConversion()
public void setNullConversion(mixed $value)

how the null and empty strings are converted

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
password property
public string $password;

the password for establishing DB connection. Defaults to empty string.

pdoInstance property read-only
public PDO getPdoInstance()

the PDO instance, null if the connection is not established yet

persistent property
public boolean getPersistent()
public void setPersistent(boolean $value)

whether the connection is persistent or not Some DBMS (such as sqlite) may not support this feature.

prefetch property read-only
public boolean getPrefetch()

whether the connection performs data prefetching

schema property read-only
public CDbSchema getSchema()

the database schema for the current connection

schemaCacheID property (available since v1.0.10)
public string $schemaCacheID;

the ID of the cache application component that is used to cache the table metadata. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching table metadata.

schemaCachingDuration property
public integer $schemaCachingDuration;

number of seconds that table metadata can remain valid in cache. Use 0 or negative value to indicate not caching schema. If greater than 0 and the primary cache is enabled, the table metadata will be cached.

See Also

  • schemaCachingExclude
schemaCachingExclude property
public array $schemaCachingExclude;

list of tables whose metadata should NOT be cached. Defaults to empty array.

See Also

  • schemaCachingDuration
serverInfo property read-only
public string getServerInfo()

the information of DBMS server

serverVersion property read-only
public string getServerVersion()

the version information of DBMS server

stats property read-only (available since v1.0.6)
public array getStats()

Returns the statistical results of SQL executions. The results returned include the number of SQL statements executed and the total time spent. In order to use this method, enableProfiling has to be set true.

tablePrefix property (available since v1.1.0)
public string $tablePrefix;

the default prefix for table names. Defaults to null, meaning no table prefix. By setting this property, any token like 'CDbCommand::text will be replaced by 'prefixTableName', where 'prefix' refers to this property value.

timeout property read-only
public int getTimeout()

timeout settings for the connection

username property
public string $username;

the username for establishing DB connection. Defaults to empty string.

Method Details

__construct() method
public void __construct(string $dsn='', string $username='', string $password='')
$dsn | string | The Data Source Name, or DSN, contains the information required to connect to the database.
$username | string | The user name for the DSN string.
$password | string | The password for the DSN string.

Constructor. Note, the DB connection is not established when this connection instance is created. Set active property to true to establish the connection.

See Also

  • http://www.php.net/manual/en/function.PDO-construct.php
__sleep() method
public void __sleep()

Close the connection when serializing.

beginTransaction() method
public CDbTransaction beginTransaction()
{return} CDbTransaction the transaction initiated

Starts a transaction.

close() method
protected void close()

Closes the currently active DB connection. It does nothing if the connection is already closed.

createCommand() method
public CDbCommand createCommand(string $sql)
$sql | string | SQL statement associated with the new command.
{return} | CDbCommand | the DB command

Creates a command for execution.

createPdoInstance() method (available since v1.0.4)
protected PDO createPdoInstance()
{return} PDO the pdo instance

Creates the PDO instance. When some functionalities are missing in the pdo driver, we may use an adapter class to provides them.

getActive() method
public boolean getActive()
{return} boolean whether the DB connection is established

getAttribute() method
public mixed getAttribute(int $name)
$name | int | the attribute to be queried
{return} | mixed | the corresponding attribute information

Obtains a specific DB connection attribute information.

See Also

  • http://www.php.net/manual/en/function.PDO-getAttribute.php
getAutoCommit() method
public boolean getAutoCommit()
{return} boolean whether creating or updating a DB record will be automatically committed. Some DBMS (such as sqlite) may not support this feature.

getAvailableDrivers() method
public static array getAvailableDrivers()
{return} array list of available PDO drivers

See Also

  • http://www.php.net/manual/en/function.PDO-getAvailableDrivers.php
getClientVersion() method
public string getClientVersion()
{return} string the version information of the DB driver

getColumnCase() method
public mixed getColumnCase()
{return} mixed the case of the column names

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
getCommandBuilder() method (available since v1.0.4)
public CDbCommandBuilder getCommandBuilder()
{return} CDbCommandBuilder the command builder

Returns the SQL command builder for the current DB connection.

getConnectionStatus() method
public string getConnectionStatus()
{return} string the status of the connection Some DBMS (such as sqlite) may not support this feature.

getCurrentTransaction() method
public CDbTransaction getCurrentTransaction()
{return} CDbTransaction the currently active transaction. Null if no active transaction.

getDriverName() method
public string getDriverName()
{return} string name of the DB driver

getLastInsertID() method
public string getLastInsertID(string $sequenceName='')
$sequenceName | string | name of the sequence object (required by some DBMS)
{return} | string | the row ID of the last row inserted, or the last value retrieved from the sequence object

Returns the ID of the last inserted row or sequence value.

See Also

  • http://www.php.net/manual/en/function.PDO-lastInsertId.php
getNullConversion() method
public mixed getNullConversion()
{return} mixed how the null and empty strings are converted

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
getPdoInstance() method
public PDO getPdoInstance()
{return} PDO the PDO instance, null if the connection is not established yet

getPdoType() method
public integer getPdoType(string $type)
$type | string | The PHP type (obtained by gettype() call).
{return} | integer | the corresponding PDO type

Determines the PDO type for the specified PHP type.

getPersistent() method
public boolean getPersistent()
{return} boolean whether the connection is persistent or not Some DBMS (such as sqlite) may not support this feature.

getPrefetch() method
public boolean getPrefetch()
{return} boolean whether the connection performs data prefetching

getSchema() method
public CDbSchema getSchema()
{return} CDbSchema the database schema for the current connection

getServerInfo() method
public string getServerInfo()
{return} string the information of DBMS server

getServerVersion() method
public string getServerVersion()
{return} string the version information of DBMS server

getStats() method (available since v1.0.6)
public array getStats()
{return} array the first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution.

Returns the statistical results of SQL executions. The results returned include the number of SQL statements executed and the total time spent. In order to use this method, enableProfiling has to be set true.

getTimeout() method
public int getTimeout()
{return} int timeout settings for the connection

init() method
public void init()

Initializes the component. This method is required by IApplicationComponent and is invoked by application when the CDbConnection is used as an application component. If you override this method, make sure to call the parent implementation so that the component can be marked as initialized.

initConnection() method
protected void initConnection(PDO $pdo)
$pdo PDO the PDO instance

Initializes the open db connection. This method is invoked right after the db connection is established. The default implementation is to set the charset for MySQL and PostgreSQL database connections.

open() method
protected void open()

Opens DB connection if it is currently not

quoteColumnName() method
public string quoteColumnName(string $name)
$name | string | column name
{return} | string | the properly quoted column name

Quotes a column name for use in a query.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

quoteValue() method
public string quoteValue(string $str)
$str | string | string to be quoted
{return} | string | the properly quoted string

Quotes a string value for use in a query.

See Also

  • http://www.php.net/manual/en/function.PDO-quote.php
setActive() method
public void setActive(boolean $value)
$value boolean whether to open or close DB connection

Open or close the DB connection.

setAttribute() method
public void setAttribute(int $name, mixed $value)
$name | int | the attribute to be set
$value | mixed | the attribute value

Sets an attribute on the database connection.

See Also

  • http://www.php.net/manual/en/function.PDO-setAttribute.php
setAutoCommit() method
public void setAutoCommit(boolean $value)
$value boolean whether creating or updating a DB record will be automatically committed. Some DBMS (such as sqlite) may not support this feature.

setColumnCase() method
public void setColumnCase(mixed $value)
$value mixed the case of the column names

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
setNullConversion() method
public void setNullConversion(mixed $value)
$value mixed how the null and empty strings are converted

See Also

  • http://www.php.net/manual/en/pdo.setattribute.php
setPersistent() method
public void setPersistent(boolean $value)
$value boolean whether the connection is persistent or not Some DBMS (such as sqlite) may not support this feature.


CDbDataReader

Package | system.db
Inheritance | class CDbDataReader » CComponent
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CDbDataReader.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbDataReader represents a forward-only stream of rows from a query result set.

To read the current row of data, call read. The method readAll returns all the rows in a single array.

One can also retrieve the rows of data in CDbDataReader by using foreach:
foreach($reader as $row)
    // $row represents a row of data
Since CDbDataReader is a forward-only stream, you can only traverse it once.

It is possible to use a specific mode of data fetching by setting FetchMode. See http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php for more details.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
columnCount | int | the number of columns in the result set. | CDbDataReader
isClosed | boolean | whether the reader is closed or not. | CDbDataReader
rowCount | int | number of rows contained in the result. | CDbDataReader

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbDataReader
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindColumn() | Binds a column to a PHP variable. | CDbDataReader
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
close() | Closes the reader. | CDbDataReader
current() | Returns the current row. | CDbDataReader
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumnCount() |  | CDbDataReader
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsClosed() |  | CDbDataReader
getRowCount() |  | CDbDataReader
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
key() | Returns the index of the current row. | CDbDataReader
next() | Moves the internal pointer to the next row. | CDbDataReader
nextResult() | Advances the reader to the next result when reading the results of a batch of statements. | CDbDataReader
raiseEvent() | Raises an event. | CComponent
read() | Advances the reader to the next row in a result set. | CDbDataReader
readAll() | Reads the whole result set into an array. | CDbDataReader
readColumn() | Returns a single column from the next row of a result set. | CDbDataReader
readObject() | Returns an object populated with the next row of data. | CDbDataReader
rewind() | Resets the iterator to the initial state. | CDbDataReader
setFetchMode() |  | CDbDataReader
valid() | Returns whether there is a row of data at current position. | CDbDataReader

Property Details

columnCount property read-only
public int getColumnCount()

the number of columns in the result set. Note, even there's no row in the reader, this still gives correct column number.

isClosed property read-only
public boolean getIsClosed()

whether the reader is closed or not.

rowCount property read-only
public int getRowCount()

number of rows contained in the result. Note, most DBMS may not give a meaningful count. In this case, use "SELECT COUNT(*) FROM tableName" to obtain the number of rows.

Method Details

__construct() method
public void __construct(CDbCommand $command)
$command CDbCommand the command generating the query result

Constructor.

bindColumn() method
public void bindColumn(mixed $column, mixed $value, int $dataType=NULL)
$column | mixed | Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.
$value | mixed | Name of the PHP variable to which the column will be bound.
$dataType | int | Data type of the parameter

Binds a column to a PHP variable. When rows of data are being fetched, the corresponding column value will be set in the variable. Note, the fetch mode must include PDO::FETCH_BOUND.

See Also

  • http://www.php.net/manual/en/function.PDOStatement-bindColumn.php
close() method
public void close()

Closes the reader. This frees up the resources allocated for executing this SQL statement. Read attemps after this method call are unpredictable.

current() method
public mixed current()
{return} mixed the current row.

Returns the current row. This method is required by the interface Iterator.

getColumnCount() method
public int getColumnCount()
{return} int the number of columns in the result set. Note, even there's no row in the reader, this still gives correct column number.

getIsClosed() method
public boolean getIsClosed()
{return} boolean whether the reader is closed or not.

getRowCount() method
public int getRowCount()
{return} int number of rows contained in the result. Note, most DBMS may not give a meaningful count. In this case, use "SELECT COUNT(*) FROM tableName" to obtain the number of rows.

key() method
public integer key()
{return} integer the index of the current row.

Returns the index of the current row. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next row. This method is required by the interface Iterator.

nextResult() method
public void nextResult()

Advances the reader to the next result when reading the results of a batch of statements. This method is only useful when there are multiple result sets returned by the query. Not all DBMS support this feature.

read() method
public array|false read()
{return} array|false the current row, false if no more row available

Advances the reader to the next row in a result set.

readAll() method
public array readAll()
{return} array the result set (each array element represents a row of data). An empty array will be returned if the result contains no row.

Reads the whole result set into an array.

readColumn() method
public mixed|false readColumn(int $columnIndex)
$columnIndex | int | zero-based column index
{return} | mixed|false | the column of the current row, false if no more row available

Returns a single column from the next row of a result set.

readObject() method
public mixed|false readObject(string $className, array $fields)
$className | string | class name of the object to be created and populated
$fields | array | Elements of this array are passed to the constructor
{return} | mixed|false | the populated object, false if no more row of data available

Returns an object populated with the next row of data.

rewind() method
public void rewind()

Resets the iterator to the initial state. This method is required by the interface Iterator.

setFetchMode() method
public void setFetchMode($mode)
$mode

See Also

  • http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
valid() method
public boolean valid()
{return} boolean whether there is a row of data at current position.

Returns whether there is a row of data at current position. This method is required by the interface Iterator.


CDbException

Package | system.db
Inheritance | class CDbException » CException » Exception
Since | 1.0
Version | $Id: CDbException.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbException represents an exception that is caused by some DB-related operations.

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
code |  |  | Exception
file |  |  | Exception
line |  |  | Exception
message |  |  | Exception

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() |  | Exception
__toString() |  | Exception
getCode() |  | Exception
getFile() |  | Exception
getLine() |  | Exception
getMessage() |  | Exception
getTrace() |  | Exception
getTraceAsString() |  | Exception


CDbTransaction

Package | system.db
Inheritance | class CDbTransaction » CComponent
Since | 1.0
Version | $Id: CDbTransaction.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbTransaction represents a DB transaction.

It is usually created by calling CDbConnection::beginTransaction.

The following code is a common scenario of using transactions:
$transaction=$connection->beginTransaction();
try
{
   $connection->createCommand($sql1)->execute();
   $connection->createCommand($sql2)->execute();
   //.... other SQL executions
   $transaction->commit();
}
catch(Exception $e)
{
   $transaction->rollBack();
}

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
active | boolean | whether this transaction is active | CDbTransaction
connection | CDbConnection | the DB connection for this transaction | CDbTransaction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbTransaction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
commit() | Commits a transaction. | CDbTransaction
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getActive() |  | CDbTransaction
getConnection() |  | CDbTransaction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
rollback() | Rolls back a transaction. | CDbTransaction

Protected Methods

Hide inherited methods

Method | Description | Defined By
setActive() |  | CDbTransaction

Property Details

active property
public boolean getActive()
protected void setActive(boolean $value)

whether this transaction is active

connection property read-only
public CDbConnection getConnection()

the DB connection for this transaction

Method Details

__construct() method
public void __construct(CDbConnection $connection)
$connection CDbConnection the connection associated with this transaction

Constructor.

See Also

  • CDbConnection::beginTransaction
commit() method
public void commit()

Commits a transaction.

getActive() method
public boolean getActive()
{return} boolean whether this transaction is active

getConnection() method
public CDbConnection getConnection()
{return} CDbConnection the DB connection for this transaction

rollback() method
public void rollback()

Rolls back a transaction.

setActive() method
protected void setActive(boolean $value)
$value boolean whether this transaction is active


CActiveFinder

Package | system.db.ar
Inheritance | class CActiveFinder » CComponent
Since | 1.0
Version | $Id: CActiveFinder.php 1869 2010-03-09 22:02:12Z qiang.xue $
CActiveFinder implements eager loading and lazy loading of related active records.

When used in eager loading, this class provides the same set of find methods as CActiveRecord.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
baseLimited | boolean | whether the base model has limit or offset. | CActiveFinder
joinAll | boolean | join all tables all at once. | CActiveFinder

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CActiveFinder
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
count() | This is the relational version of CActiveRecord::count(). | CActiveFinder
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
find() | This is the relational version of CActiveRecord::find(). | CActiveFinder
findAll() | This is the relational version of CActiveRecord::findAll(). | CActiveFinder
findAllByAttributes() | This is the relational version of CActiveRecord::findAllByAttributes(). | CActiveFinder
findAllByPk() | This is the relational version of CActiveRecord::findAllByPk(). | CActiveFinder
findAllBySql() | This is the relational version of CActiveRecord::findAllBySql(). | CActiveFinder
findByAttributes() | This is the relational version of CActiveRecord::findByAttributes(). | CActiveFinder
findByPk() | This is the relational version of CActiveRecord::findByPk(). | CActiveFinder
findBySql() | This is the relational version of CActiveRecord::findBySql(). | CActiveFinder
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
lazyFind() | Finds the related objects for the specified active record. | CActiveFinder
query() | Performs the relational query based on the given DB criteria. | CActiveFinder
raiseEvent() | Raises an event. | CComponent
together() | Uses the most aggressive join approach. | CActiveFinder

Property Details

baseLimited property (available since v1.0.2)
public boolean $baseLimited;

whether the base model has limit or offset. This property is internally used.

joinAll property (available since v1.0.2)
public boolean $joinAll;

join all tables all at once. Defaults to false. This property is internally used.

Method Details

__construct() method
public void __construct(CActiveRecord $model, mixed $with)
$model | CActiveRecord | the model that initiates the active finding process
$with | mixed | the relation names to be actively looked for

Constructor. A join tree is built up based on the declared relationships between active record classes.

count() method (available since v1.0.3)
public void count($condition='', $params=array ( ))
$condition
$params

This is the relational version of CActiveRecord::count().

find() method
public void find($condition='', $params=array ( ))
$condition
$params

This is the relational version of CActiveRecord::find().

findAll() method
public void findAll($condition='', $params=array ( ))
$condition
$params

This is the relational version of CActiveRecord::findAll().

findAllByAttributes() method
public void findAllByAttributes($attributes, $condition='', $params=array ( ))
$attributes
$condition
$params

This is the relational version of CActiveRecord::findAllByAttributes().

findAllByPk() method
public void findAllByPk($pk, $condition='', $params=array ( ))
$pk
$condition
$params

This is the relational version of CActiveRecord::findAllByPk().

findAllBySql() method
public void findAllBySql($sql, $params=array ( ))
$sql
$params

This is the relational version of CActiveRecord::findAllBySql().

findByAttributes() method
public void findByAttributes($attributes, $condition='', $params=array ( ))
$attributes
$condition
$params

This is the relational version of CActiveRecord::findByAttributes().

findByPk() method
public void findByPk($pk, $condition='', $params=array ( ))
$pk
$condition
$params

This is the relational version of CActiveRecord::findByPk().

findBySql() method
public void findBySql($sql, $params=array ( ))
$sql
$params

This is the relational version of CActiveRecord::findBySql().

lazyFind() method
public void lazyFind(CActiveRecord $baseRecord)
$baseRecord CActiveRecord the base record whose related objects are to be loaded

Finds the related objects for the specified active record. This method is internally invoked by CActiveRecord to support lazy loading.

query() method
public mixed query(CDbCriteria $criteria, boolean $all=false)
$criteria | CDbCriteria | the DB criteria
$all | boolean | whether to bring back all records
{return} | mixed | the query result

Performs the relational query based on the given DB criteria. Do not call this method. This method is used internally.

together() method (available since v1.0.2)
public CActiveFinder together()
{return} CActiveFinder the finder object

Uses the most aggressive join approach. By calling this method, even if there is LIMIT/OFFSET option set for the primary table query, we will still use a single SQL statement. By default (without calling this method), the primary table will be queried by itself so that LIMIT/OFFSET can be correctly applied.


CActiveRecord

All Packages | Properties | Methods | Events
Package | system.db.ar
Inheritance | abstract class CActiveRecord » CModel » CComponent
Implements | ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CActiveRecord is the base class for classes representing relational data.

It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique. Please check the Guide for more details about this class.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | Returns all column attribute values. | CActiveRecord
commandBuilder | CDbCommandBuilder | the command builder used by this AR | CActiveRecord
db | CDbConnection | the default database connection for all active record classes. | CActiveRecord
dbConnection | CDbConnection | Returns the database connection used by active record. | CActiveRecord
dbCriteria | CDbCriteria | Returns the query criteria associated with this model. | CActiveRecord
errors | array | Returns the errors for all attribute or a single attribute. | CModel
isNewRecord | boolean | whether the record is new and should be inserted when calling save. | CActiveRecord
iterator | CMapIterator | Returns an iterator for traversing the attributes in the model. | CModel
metaData | CActiveRecordMetaData | the meta for this AR class. | CActiveRecord
oldPrimaryKey | mixed | Returns the old primary key value. | CActiveRecord
primaryKey | mixed | the primary key value. | CActiveRecord
safeAttributeNames | array | Returns the attribute names that are safe to be massively assigned. | CModel
scenario | string | Returns the scenario that this model is used in. | CModel
tableAlias | string | Returns the default table alias to be used by the find methods. | CActiveRecord
tableSchema | CDbTableSchema | the metadata of the table that this AR belongs to | CActiveRecord
validators | array | Returns the validators applicable to the current scenario. | CModel

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CActiveRecord
__construct() | Constructor. | CActiveRecord
__get() | PHP getter magic method. | CActiveRecord
__isset() | Checks if a property value is null. | CActiveRecord
__set() | PHP setter magic method. | CActiveRecord
__sleep() | PHP sleep magic method. | CActiveRecord
__unset() | Sets a component property to be null. | CActiveRecord
addError() | Adds a new error to the specified attribute. | CModel
addErrors() | Adds a list of errors. | CModel
addRelatedRecord() | Adds a related object to this record. | CActiveRecord
afterFindInternal() | Calls afterFind. | CActiveRecord
applyScopes() | Applies the query scopes to the given criteria. | CActiveRecord
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
attributeLabels() | Returns the attribute labels. | CModel
attributeNames() | Returns the list of all attribute names of the model. | CActiveRecord
beforeFindInternal() | Calls beforeFind. | CActiveRecord
behaviors() | Returns a list of behaviors that this model should behave as. | CModel
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearErrors() | Removes errors for all attributes or a single attribute. | CModel
count() | Finds the number of rows satisfying the specified query condition. | CActiveRecord
countBySql() | Finds the number of rows using the given SQL statement. | CActiveRecord
createValidators() | Creates validator objects based on the specification in rules. | CModel
defaultScope() | Returns the default named scope that should be implicitly applied to all queries for this model. | CActiveRecord
delete() | Deletes the row corresponding to this active record. | CActiveRecord
deleteAll() | Deletes rows with the specified condition. | CActiveRecord
deleteAllByAttributes() | Deletes rows which match the specified attribute values. | CActiveRecord
deleteByPk() | Deletes rows with the specified primary key. | CActiveRecord
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
equals() | Compares this active record with another one. | CActiveRecord
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
exists() | Checks whether there is row satisfying the specified condition. | CActiveRecord
find() | Finds a single active record with the specified condition. | CActiveRecord
findAll() | Finds all active records satisfying the specified condition. | CActiveRecord
findAllByAttributes() | Finds all active records that have the specified attribute values. | CActiveRecord
findAllByPk() | Finds all active records with the specified primary keys. | CActiveRecord
findAllBySql() | Finds all active records using the specified SQL statement. | CActiveRecord
findByAttributes() | Finds a single active record that has the specified attribute values. | CActiveRecord
findByPk() | Finds a single active record with the specified primary key. | CActiveRecord
findBySql() | Finds a single active record with the specified SQL statement. | CActiveRecord
generateAttributeLabel() | Generates a user friendly attribute label. | CModel
getActiveRelation() |  | CActiveRecord
getAttribute() | Returns the named attribute value. | CActiveRecord
getAttributeLabel() | Returns the text label for the specified attribute. | CModel
getAttributes() | Returns all column attribute values. | CActiveRecord
getCommandBuilder() |  | CActiveRecord
getDbConnection() | Returns the database connection used by active record. | CActiveRecord
getDbCriteria() | Returns the query criteria associated with this model. | CActiveRecord
getError() | Returns the first error of the specified attribute. | CModel
getErrors() | Returns the errors for all attribute or a single attribute. | CModel
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsNewRecord() |  | CActiveRecord
getIterator() | Returns an iterator for traversing the attributes in the model. | CModel
getMetaData() |  | CActiveRecord
getOldPrimaryKey() | Returns the old primary key value. | CActiveRecord
getPrimaryKey() |  | CActiveRecord
getRelated() | Returns the related record(s). | CActiveRecord
getSafeAttributeNames() | Returns the attribute names that are safe to be massively assigned. | CModel
getScenario() | Returns the scenario that this model is used in. | CModel
getTableAlias() | Returns the default table alias to be used by the find methods. | CActiveRecord
getTableSchema() |  | CActiveRecord
getValidators() | Returns the validators applicable to the current scenario. | CModel
hasAttribute() |  | CActiveRecord
hasErrors() | Returns a value indicating whether there is any validation error. | CModel
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
hasRelated() | Returns a value indicating whether the named related object(s) has been loaded. | CActiveRecord
init() | Initializes this model. | CActiveRecord
insert() | Inserts a row into the table based on this active record attributes. | CActiveRecord
isAttributeRequired() | Returns a value indicating whether the attribute is required. | CModel
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | CModel
model() | Returns the static model of the specified AR class. | CActiveRecord
offsetExists() | Returns whether there is an element at the specified offset. | CActiveRecord
offsetGet() | Returns the element at the specified offset. | CModel
offsetSet() | Sets the element at the specified offset. | CModel
offsetUnset() | Unsets the element at the specified offset. | CModel
onAfterConstruct() | This event is raised after the record instance is created by new operator. | CActiveRecord
onAfterDelete() | This event is raised after the record is deleted. | CActiveRecord
onAfterFind() | This event is raised after the record is instantiated by a find method. | CActiveRecord
onAfterSave() | This event is raised after the record is saved. | CActiveRecord
onAfterValidate() | This event is raised after the validation is performed. | CModel
onBeforeDelete() | This event is raised before the record is deleted. | CActiveRecord
onBeforeFind() | This event is raised before an AR finder performs a find call. | CActiveRecord
onBeforeSave() | This event is raised before the record is saved. | CActiveRecord
onBeforeValidate() | This event is raised before the validation is performed. | CModel
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | CModel
populateRecord() | Creates an active record with the given attributes. | CActiveRecord
populateRecords() | Creates a list of active records based on the input data. | CActiveRecord
primaryKey() | Returns the primary key of the associated database table. | CActiveRecord
raiseEvent() | Raises an event. | CComponent
refresh() | Repopulates this active record with the latest data. | CActiveRecord
refreshMetaData() | Refreshes the meta data for this AR class. | CActiveRecord
relations() | This method should be overridden to declare related objects. | CActiveRecord
rules() | Returns the validation rules for attributes. | CModel
save() | Saves the current record. | CActiveRecord
saveAttributes() | Saves a selected list of attributes. | CActiveRecord
scopes() | Returns the declaration of named scopes. | CActiveRecord
setAttribute() | Sets the named attribute value. | CActiveRecord
setAttributes() | Sets the attribute values in a massive way. | CModel
setIsNewRecord() |  | CActiveRecord
setPrimaryKey() | Sets the primary key value. | CActiveRecord
setScenario() |  | CModel
tableName() | Returns the name of the associated database table. | CActiveRecord
update() | Updates the row represented by this active record. | CActiveRecord
updateAll() | Updates records with the specified condition. | CActiveRecord
updateByPk() | Updates records with the specified primary key(s). | CActiveRecord
updateCounters() | Updates one or several counter columns. | CActiveRecord
validate() | Performs the validation. | CModel
with() | Specifies which related objects should be eagerly loaded. | CActiveRecord

Protected Methods

Hide inherited methods

Method | Description | Defined By
afterConstruct() | This method is invoked after a record instance is created by new operator. | CActiveRecord
afterDelete() | This method is invoked after deleting a record. | CActiveRecord
afterFind() | This method is invoked after each record is instantiated by a find method. | CActiveRecord
afterSave() | This method is invoked after saving a record successfully. | CActiveRecord
afterValidate() | This method is invoked after validation ends. | CModel
beforeDelete() | This method is invoked before deleting a record. | CActiveRecord
beforeFind() | This method is invoked before an AR finder executes a find call. | CActiveRecord
beforeSave() | This method is invoked before saving a record (after validation, if any). | CActiveRecord
beforeValidate() | This method is invoked before validation starts. | CModel
instantiate() | Creates an active record instance. | CActiveRecord

Events

Hide inherited events

Event | Description | Defined By
onBeforeSave | This event is raised before the record is saved. | CActiveRecord
onAfterSave | This event is raised after the record is saved. | CActiveRecord
onBeforeDelete | This event is raised before the record is deleted. | CActiveRecord
onAfterDelete | This event is raised after the record is deleted. | CActiveRecord
onAfterConstruct | This event is raised after the record instance is created by new operator. | CActiveRecord
onBeforeFind | This event is raised before an AR finder performs a find call. | CActiveRecord
onAfterFind | This event is raised after the record is instantiated by a find method. | CActiveRecord
onBeforeValidate | This event is raised before the validation is performed. | CModel
onAfterValidate | This event is raised after the validation is performed. | CModel
onUnsafeAttribute | This method is invoked when an unsafe attribute is being massively assigned. | CModel

Property Details

attributes property
public array getAttributes(mixed $names=true)
public void setAttributes(array $values, boolean $safeOnly=true)

Returns all column attribute values. Note, related objects are not returned.

commandBuilder property read-only
public CDbCommandBuilder getCommandBuilder()

the command builder used by this AR

db property
public static CDbConnection $db;

the default database connection for all active record classes. By default, this is the 'db' application component.

See Also

  • getDbConnection
dbConnection property read-only
public CDbConnection getDbConnection()

Returns the database connection used by active record. By default, the "db" application component is used as the database connection. You may override this method if you want to use a different database connection.

dbCriteria property read-only (available since v1.0.5)
public CDbCriteria getDbCriteria(boolean $createIfNull=true)

Returns the query criteria associated with this model.

isNewRecord property
public boolean getIsNewRecord()
public void setIsNewRecord(boolean $value)

whether the record is new and should be inserted when calling save. This property is automatically set in constructor and populateRecord. Defaults to false, but it will be set to true if the instance is created using the new operator.

metaData property read-only
public CActiveRecordMetaData getMetaData()

the meta for this AR class.

oldPrimaryKey property read-only (available since v1.1.0)
public mixed getOldPrimaryKey()

Returns the old primary key value. This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findAll()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.

primaryKey property
public mixed getPrimaryKey()
public void setPrimaryKey(mixed $value)

the primary key value. An array (column name=>column value) is returned if the primary key is composite. If primary key is not defined, null will be returned.

tableAlias property read-only (available since v1.1.1)
public string getTableAlias(boolean $quote=false)

Returns the default table alias to be used by the find methods. This method will return the 'alias' option if it is set in defaultScope. Otherwise, it will return 't' as the default alias.

tableSchema property read-only
public CDbTableSchema getTableSchema()

the metadata of the table that this AR belongs to

Method Details

__call() method (available since v1.0.5)
public mixed __call(string $name, array $parameters)
$name | string | the method name
$parameters | array | method parameters
{return} | mixed | the method return value

Calls the named method which is not a class method. Do not call this method. This is a PHP magic method that we override to implement the named scope feature.

__construct() method
public void __construct(string $scenario='insert')
$scenario string scenario name. See CModel::scenario for more details about this parameter.

Constructor.

__get() method
public mixed __get(string $name)
$name | string | property name
{return} | mixed | property value

PHP getter magic method. This method is overridden so that AR attributes can be accessed like properties.

See Also

  • getAttribute
__isset() method (available since v1.0.1)
public boolean __isset(string $name)
$name | string | the property name or the event name
{return} | boolean | whether the property value is null

Checks if a property value is null. This method overrides the parent implementation by checking if the named attribute is null or not.

__set() method
public void __set(string $name, mixed $value)
$name | string | property name
$value | mixed | property value

PHP setter magic method. This method is overridden so that AR attributes can be accessed like properties.

__sleep() method
public void __sleep()

PHP sleep magic method. This method ensures that the model meta data reference is set to null.

__unset() method (available since v1.0.1)
public void __unset(string $name)
$name string the property name or the event name

Sets a component property to be null. This method overrides the parent implementation by clearing the specified attribute value.

addRelatedRecord() method
public void addRelatedRecord(string $name, mixed $record, mixed $index)
$name | string | attribute name
$record | mixed | the related record
$index | mixed | the index value in the related object collection. If true, it means using zero-based integer index. If false, it means a HAS_ONE or BELONGS_TO object and no index is needed.

Adds a related object to this record. This method is used internally by CActiveFinder to populate related objects.

afterConstruct() method
protected void afterConstruct()

This method is invoked after a record instance is created by new operator. The default implementation raises the onAfterConstruct event. You may override this method to do postprocessing after record creation. Make sure you call the parent implementation so that the event is raised properly.

afterDelete() method
protected void afterDelete()

This method is invoked after deleting a record. The default implementation raises the onAfterDelete event. You may override this method to do postprocessing after the record is deleted. Make sure you call the parent implementation so that the event is raised properly.

afterFind() method
protected void afterFind()

This method is invoked after each record is instantiated by a find method. The default implementation raises the onAfterFind event. You may override this method to do postprocessing after each newly found record is instantiated. Make sure you call the parent implementation so that the event is raised properly.

afterFindInternal() method (available since v1.0.3)
public void afterFindInternal()

Calls afterFind. This method is internally used.

afterSave() method
protected void afterSave()

This method is invoked after saving a record successfully. The default implementation raises the onAfterSave event. You may override this method to do postprocessing after record saving. Make sure you call the parent implementation so that the event is raised properly.

applyScopes() method (available since v1.0.12)
public void applyScopes(CDbCriteria $criteria)
$criteria CDbCriteria the query criteria. This parameter may be modified by merging dbCriteria.

Applies the query scopes to the given criteria. This method merges dbCriteria with the given criteria parameter. It then resets dbCriteria to be null.

attributeNames() method (available since v1.0.1)
public array attributeNames()
{return} array list of attribute names.

Returns the list of all attribute names of the model. This would return all column names of the table associated with this AR class.

beforeDelete() method
protected boolean beforeDelete()
{return} boolean whether the record should be deleted. Defaults to true.

This method is invoked before deleting a record. The default implementation raises the onBeforeDelete event. You may override this method to do any preparation work for record deletion. Make sure you call the parent implementation so that the event is raised properly.

beforeFind() method (available since v1.0.9)
protected void beforeFind()

This method is invoked before an AR finder executes a find call. The find calls include find, findAll, findByPk, findAllByPk, findByAttributes and findAllByAttributes. The default implementation raises the onBeforeFind event. If you override this method, make sure you call the parent implementation so that the event is raised properly.

beforeFindInternal() method (available since v1.0.11)
public void beforeFindInternal()

Calls beforeFind. This method is internally used.

beforeSave() method
protected boolean beforeSave()
{return} boolean whether the saving should be executed. Defaults to true.

This method is invoked before saving a record (after validation, if any). The default implementation raises the onBeforeSave event. You may override this method to do any preparation work for record saving. Use isNewRecord to determine whether the saving is for inserting or updating record. Make sure you call the parent implementation so that the event is raised properly.

count() method
public integer count(mixed $condition='', array $params=array ( ))
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows satisfying the specified query condition.

Finds the number of rows satisfying the specified query condition. See find() for detailed explanation about $condition and $params.

countBySql() method
public integer countBySql(string $sql, array $params=array ( ))
$sql | string | the SQL statement
$params | array | parameters to be bound to the SQL statement
{return} | integer | the number of rows using the given SQL statement.

Finds the number of rows using the given SQL statement.

defaultScope() method (available since v1.0.5)
public array defaultScope()
{return} array the query criteria. This will be used as the parameter to the constructor of CDbCriteria.

Returns the default named scope that should be implicitly applied to all queries for this model. Note, default scope only applies to SELECT queries. It is ignored for INSERT, UPDATE and DELETE queries. The default implementation simply returns an empty array. You may override this method if the model needs to be queried with some default criteria (e.g. only active records should be returned).

delete() method
public boolean delete()
{return} boolean whether the deletion is successful.

Deletes the row corresponding to this active record.

deleteAll() method
public integer deleteAll(mixed $condition='', array $params=array ( ))
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows deleted

Deletes rows with the specified condition. See find() for detailed explanation about $condition and $params.

deleteAllByAttributes() method (available since v1.0.9)
public CActiveRecord deleteAllByAttributes(array $attributes, mixed $condition='', array $params=array ( ))
$attributes | array | list of attribute values (indexed by attribute names) that the active records should match. Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | CActiveRecord | the record found. Null if none is found.

Deletes rows which match the specified attribute values. See find() for detailed explanation about $condition and $params.

deleteByPk() method
public integer deleteByPk(mixed $pk, mixed $condition='', array $params=array ( ))
$pk | mixed | primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows deleted

Deletes rows with the specified primary key. See find() for detailed explanation about $condition and $params.

equals() method
public boolean equals($record)
$record |  |
{return} | boolean | whether the two active records refer to the same row in the database table.

Compares this active record with another one. The comparison is made by comparing the primary key values of the two active records.

exists() method
public boolean exists(mixed $condition, array $params=array ( ))
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | boolean | whether there is row satisfying the specified condition.

Checks whether there is row satisfying the specified condition. See find() for detailed explanation about $condition and $params.

find() method
public CActiveRecord find(mixed $condition='', array $params=array ( ))
$condition | mixed | query condition or criteria. If a string, it is treated as query condition (the WHERE clause); If an array, it is treated as the initial values for constructing a CDbCriteria object; Otherwise, it should be an instance of CDbCriteria.
$params | array | parameters to be bound to an SQL statement. This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
{return} | CActiveRecord | the record found. Null if no record is found.

Finds a single active record with the specified condition.

findAll() method
public array findAll(mixed $condition='', array $params=array ( ))
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | array | list of active records satisfying the specified condition. An empty array is returned if none is found.

Finds all active records satisfying the specified condition. See find() for detailed explanation about $condition and $params.

findAllByAttributes() method
public array findAllByAttributes(array $attributes, mixed $condition='', array $params=array ( ))
$attributes | array | list of attribute values (indexed by attribute names) that the active records should match. Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | array | the records found. An empty array is returned if none is found.

Finds all active records that have the specified attribute values. See find() for detailed explanation about $condition and $params.

findAllByPk() method
public array findAllByPk(mixed $pk, mixed $condition='', array $params=array ( ))
$pk | mixed | primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | array | the records found. An empty array is returned if none is found.

Finds all active records with the specified primary keys. See find() for detailed explanation about $condition and $params.

findAllBySql() method
public array findAllBySql(string $sql, array $params=array ( ))
$sql | string | the SQL statement
$params | array | parameters to be bound to the SQL statement
{return} | array | the records found. An empty array is returned if none is found.

Finds all active records using the specified SQL statement.

findByAttributes() method
public CActiveRecord findByAttributes(array $attributes, mixed $condition='', array $params=array ( ))
$attributes | array | list of attribute values (indexed by attribute names) that the active records should match. Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | CActiveRecord | the record found. Null if none is found.

Finds a single active record that has the specified attribute values. See find() for detailed explanation about $condition and $params.

findByPk() method
public CActiveRecord findByPk(mixed $pk, mixed $condition='', array $params=array ( ))
$pk | mixed | primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | CActiveRecord | the record found. Null if none is found.

Finds a single active record with the specified primary key. See find() for detailed explanation about $condition and $params.

findBySql() method
public CActiveRecord findBySql(string $sql, array $params=array ( ))
$sql | string | the SQL statement
$params | array | parameters to be bound to the SQL statement
{return} | CActiveRecord | the record found. Null if none is found.

Finds a single active record with the specified SQL statement.

getActiveRelation() method
public CActiveRelation getActiveRelation(string $name)
$name | string | the relation name
{return} | CActiveRelation | the named relation declared for this AR class. Null if the relation does not exist.

getAttribute() method
public mixed getAttribute(string $name)
$name | string | the attribute name
{return} | mixed | the attribute value. Null if the attribute is not set or does not exist.

Returns the named attribute value. If this is a new record and the attribute is not set before, the default column value will be returned. If this record is the result of a query and the attribute is not loaded, null will be returned. You may also use $this->AttributeName to obtain the attribute value.

See Also

  • hasAttribute
getAttributes() method
public array getAttributes(mixed $names=true)
$names | mixed | names of attributes whose value needs to be returned. If this is true (default), then all attribute values will be returned, including those that are not loaded from DB (null will be returned for those attributes). If this is null, all attributes except those that are not loaded from DB will be returned.
{return} | array | attribute values indexed by attribute names.

Returns all column attribute values. Note, related objects are not returned.

getCommandBuilder() method
public CDbCommandBuilder getCommandBuilder()
{return} CDbCommandBuilder the command builder used by this AR

getDbConnection() method
public CDbConnection getDbConnection()
{return} CDbConnection the database connection used by active record.

Returns the database connection used by active record. By default, the "db" application component is used as the database connection. You may override this method if you want to use a different database connection.

getDbCriteria() method (available since v1.0.5)
public CDbCriteria getDbCriteria(boolean $createIfNull=true)
$createIfNull | boolean | whether to create a criteria instance if it does not exist. Defaults to true.
{return} | CDbCriteria | the query criteria that is associated with this model. This criteria is mainly used by named scope feature to accumulate different criteria specifications.

Returns the query criteria associated with this model.

getIsNewRecord() method
public boolean getIsNewRecord()
{return} boolean whether the record is new and should be inserted when calling save. This property is automatically set in constructor and populateRecord. Defaults to false, but it will be set to true if the instance is created using the new operator.

getMetaData() method
public CActiveRecordMetaData getMetaData()
{return} CActiveRecordMetaData the meta for this AR class.

getOldPrimaryKey() method (available since v1.1.0)
public mixed getOldPrimaryKey()
{return} mixed the old primary key value. An array (column name=>column value) is returned if the primary key is composite. If primary key is not defined, null will be returned.

Returns the old primary key value. This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findAll()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.

getPrimaryKey() method
public mixed getPrimaryKey()
{return} mixed the primary key value. An array (column name=>column value) is returned if the primary key is composite. If primary key is not defined, null will be returned.

getRelated() method (available since v1.0.2)
public mixed getRelated(string $name, boolean $refresh=false, array $params=array ( ))
$name | string | the relation name (see relations)
$refresh | boolean | whether to reload the related objects from database. Defaults to false.
$params | array | additional parameters that customize the query conditions as specified in the relation declaration. This parameter has been available since version 1.0.5.
{return} | mixed | the related object(s).

Returns the related record(s). This method will return the related record(s) of the current record. If the relation is HAS_ONE or BELONGS_TO, it will return a single object or null if the object does not exist. If the relation is HAS_MANY or MANY_MANY, it will return an array of objects or an empty array.

getTableAlias() method (available since v1.1.1)
public string getTableAlias(boolean $quote=false)
$quote | boolean | whether to quote the alias name
{return} | string | the default table alias

Returns the default table alias to be used by the find methods. This method will return the 'alias' option if it is set in defaultScope. Otherwise, it will return 't' as the default alias.

getTableSchema() method
public CDbTableSchema getTableSchema()
{return} CDbTableSchema the metadata of the table that this AR belongs to

hasAttribute() method
public boolean hasAttribute(string $name)
$name | string | attribute name
{return} | boolean | whether this AR has the named attribute (table column).

hasRelated() method (available since v1.0.3)
public booolean hasRelated(string $name)
$name | string | the relation name
{return} | booolean | a value indicating whether the named related object(s) has been loaded.

Returns a value indicating whether the named related object(s) has been loaded.

init() method (available since v1.0.8)
public void init()

Initializes this model. This method is invoked when an AR instance is newly created and has its scenario set. You may override this method to provide code that is needed to initialize the model (e.g. setting initial property values.)

insert() method
public boolean insert(array $attributes=NULL)
$attributes | array | list of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.
{return} | boolean | whether the attributes are valid and the record is inserted successfully.

Inserts a row into the table based on this active record attributes. If the table's primary key is auto-incremental and is null before insertion, it will be populated with the actual value after insertion. Note, validation is not performed in this method. You may call validate to perform the validation. After the record is inserted to DB successfully, its isNewRecord property will be set false, and its scenario property will be set to be 'update'.

instantiate() method (available since v1.0.2)
protected CActiveRecord instantiate(array $attributes)
$attributes | array | list of attribute values for the active records.
{return} | CActiveRecord | the active record

Creates an active record instance. This method is called by populateRecord and populateRecords. You may override this method if the instance being created depends the attributes that are to be populated to the record. For example, by creating a record based on the value of a column, you may implement the so-called single-table inheritance mapping.

model() method
public static CActiveRecord model(string $className='CActiveRecord')
$className | string | active record class name.
{return} | CActiveRecord | active record model instance.

Returns the static model of the specified AR class. The model returned is a static instance of the AR class. It is provided for invoking class-level methods (something similar to static class methods.)

EVERY derived AR class must override this method as follows,

public static function model($className=__CLASS__)
{
    return parent::model($className);
}

offsetExists() method (available since v1.0.2)
public boolean offsetExists(mixed $offset)
$offset | mixed | the offset to check on
{return} | boolean |

Returns whether there is an element at the specified offset. This method is required by the interface ArrayAccess.

onAfterConstruct() method (available since v1.0.2)
public void onAfterConstruct(CEvent $event)
$event CEvent the event parameter

This event is raised after the record instance is created by new operator.

onAfterDelete() method (available since v1.0.2)
public void onAfterDelete(CEvent $event)
$event CEvent the event parameter

This event is raised after the record is deleted.

onAfterFind() method (available since v1.0.2)
public void onAfterFind(CEvent $event)
$event CEvent the event parameter

This event is raised after the record is instantiated by a find method.

onAfterSave() method (available since v1.0.2)
public void onAfterSave(CEvent $event)
$event CEvent the event parameter

This event is raised after the record is saved.

onBeforeDelete() method (available since v1.0.2)
public void onBeforeDelete(CEvent $event)
$event CEvent the event parameter

This event is raised before the record is deleted.

onBeforeFind() method (available since v1.0.9)
public void onBeforeFind(CEvent $event)
$event CEvent the event parameter

This event is raised before an AR finder performs a find call.

See Also

  • beforeFind
onBeforeSave() method (available since v1.0.2)
public void onBeforeSave(CEvent $event)
$event CEvent the event parameter

This event is raised before the record is saved.

populateRecord() method
public CActiveRecord populateRecord(array $attributes, boolean $callAfterFind=true)
$attributes | array | attribute values (column name=>column value)
$callAfterFind | boolean | whether to call afterFind after the record is populated. This parameter is added in version 1.0.3.
{return} | CActiveRecord | the newly created active record. The class of the object is the same as the model class. Null is returned if the input data is false.

Creates an active record with the given attributes. This method is internally used by the find methods.

populateRecords() method
public array populateRecords(array $data, boolean $callAfterFind=true)
$data | array | list of attribute values for the active records.
$callAfterFind | boolean | whether to call afterFind after each record is populated. This parameter is added in version 1.0.3.
{return} | array | list of active records.

Creates a list of active records based on the input data. This method is internally used by the find methods.

primaryKey() method (available since v1.0.4)
public mixed primaryKey()
{return} mixed the primary key of the associated database table. If the key is a single column, it should return the column name; If the key is a composite one consisting of several columns, it should return the array of the key column names.

Returns the primary key of the associated database table. This method is meant to be overridden in case when the table is not defined with a primary key (for some legency database). If the table is already defined with a primary key, you do not need to override this method. The default implementation simply returns null, meaning using the primary key defined in the database.

refresh() method
public boolean refresh()
{return} boolean whether the row still exists in the database. If true, the latest data will be populated to this active record.

Repopulates this active record with the latest data.

refreshMetaData() method (available since v1.0.8)
public void refreshMetaData()

Refreshes the meta data for this AR class. By calling this method, this AR class will regenerate the meta data needed. This is useful if the table schema has been changed and you want to use the latest available table schema. Make sure you have called CDbSchema::refresh before you call this method. Otherwise, old table schema data will still be used.

relations() method
public array relations()
{return} array list of related object declarations. Defaults to empty array.

This method should be overridden to declare related objects.

There are four types of relations that may exist between two active record objects:

  • BELONGS_TO: e.g. a member belongs to a team;
  • HAS_ONE: e.g. a member has at most one profile;
  • HAS_MANY: e.g. a team has many members;
  • MANY_MANY: e.g. a member has many skills and a skill belongs to a member.

By declaring these relations, CActiveRecord can bring back related objects in either lazy loading or eager loading approach, and you save the effort of writing complex JOIN SQL statements.

Each kind of related objects is defined in this method as an array with the following elements:
'varName'=>array('relationType', 'className', 'foreignKey', ...additional options)
where 'varName' refers to the name of the variable/property that the related object(s) can be accessed through; 'relationType' refers to the type of the relation, which can be one of the following four constants: self::BELONGS_TO, self::HAS_ONE, self::HAS_MANY and self::MANY_MANY; 'className' refers to the name of the active record class that the related object(s) is of; and 'foreignKey' states the foreign key that relates the two kinds of active record. Note, for composite foreign keys, they must be listed together, separating with space or comma; and for foreign keys used in MANY_MANY relation, the joining table must be declared as well (e.g. 'joinTable(fk1, fk2)').

Additional options may be specified as name-value pairs in the rest array elements:
  • 'select': string|array, a list of columns to be selected. Defaults to '*', meaning all columns. Column names should be disambiguated if they appear in an expression (e.g. COUNT(??.name) AS name_count).
  • 'condition': string, the WHERE clause. Defaults to empty. Note, column references need to be disambiguated with prefix '??.' (e.g. ??.age>20)
  • 'order': string, the ORDER BY clause. Defaults to empty. Note, column references need to be disambiguated with prefix '??.' (e.g. ??.age DESC)
  • 'with': string|array, a list of child related objects that should be loaded together with this object. Note, this is only honored by lazy loading, not eager loading.
  • 'joinType': type of join. Defaults to 'LEFT OUTER JOIN'.
  • 'alias': the alias for the table associated with this relationship. This option has been available since version 1.0.1. It defaults to null, meaning the table alias is the same as the relation name.
  • 'params': the parameters to be bound to the generated SQL statement. This should be given as an array of name-value pairs. This option has been available since version 1.0.3.
  • 'on': the ON clause. The condition specified here will be appended to the joining condition using the AND operator. This option has been available since version 1.0.2.
  • 'index': the name of the column whose values should be used as keys of the array that stores related objects. This option is only available to HAS_MANY and MANY_MANY relations. This option has been available since version 1.0.7.

The following options are available for certain relations when lazy loading:
  • 'group': string, the GROUP BY clause. Defaults to empty. Note, column references need to be disambiguated with prefix '??.' (e.g. ??.age). This option only applies to HAS_MANY and MANY_MANY relations.
  • 'having': string, the HAVING clause. Defaults to empty. Note, column references need to be disambiguated with prefix '??.' (e.g. ??.age). This option only applies to HAS_MANY and MANY_MANY relations.
  • 'limit': limit of the rows to be selected. This option does not apply to BELONGS_TO relation.
  • 'offset': offset of the rows to be selected. This option does not apply to BELONGS_TO relation.

Below is an example declaring related objects for 'Post' active record class:
return array(
    'author'=>array(self::BELONGS_TO, 'User', 'authorID'),
    'comments'=>array(self::HAS_MANY, 'Comment', 'postID', 'with'=>'author', 'order'=>'createTime DESC'),
    'tags'=>array(self::MANY_MANY, 'Tag', 'PostTag(postID, tagID)', 'order'=>'name'),
);

save() method
public boolean save(boolean $runValidation=true, array $attributes=NULL)
$runValidation | boolean | whether to perform validation before saving the record. If the validation fails, the record will not be saved to database.
$attributes | array | list of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.
{return} | boolean | whether the saving succeeds

Saves the current record.

The record is inserted as a row into the database table if its isNewRecord property is true (usually the case when the record is created using the 'new' operator). Otherwise, it will be used to update the corresponding row in the table (usually the case if the record is obtained using one of those 'find' methods.)

Validation will be performed before saving the record. If the validation fails, the record will not be saved. You can call getErrors() to retrieve the validation errors.

If the record is saved via insertion, its isNewRecord property will be set false, and its scenario property will be set to be 'update'. And if its primary key is auto-incremental and is not set before insertion, the primary key will be populated with the automatically generated key value.

saveAttributes() method
public boolean saveAttributes(array $attributes)
$attributes | array | attributes to be updated. Each element represents an attribute name or an attribute value indexed by its name. If the latter, the record's attribute will be changed accordingly before saving.
{return} | boolean | whether the update is successful

Saves a selected list of attributes. Unlike save, this method only saves the specified attributes of an existing row dataset. It thus has better performance. Note, this method does neither attribute filtering nor validation. So do not use this method with untrusted data (such as user posted data). You may consider the following alternative if you want to do so:

$postRecord=Post::model()->findByPk($postID);
$postRecord->attributes=$_POST['post'];
$postRecord->save();

scopes() method (available since v1.0.5)
public array scopes()
{return} array the scope definition. The array keys are scope names; the array values are the corresponding scope definitions. Each scope definition is represented as an array whose keys must be properties of CDbCriteria.

Returns the declaration of named scopes. A named scope represents a query criteria that can be chained together with other named scopes and applied to a query. This method should be overridden by child classes to declare named scopes for the particular AR classes. For example, the following code declares two named scopes: 'recently' and 'published'.

return array(
    'published'=>array(
          'condition'=>'status=1',
    ),
    'recently'=>array(
          'order'=>'createTime DESC',
          'limit'=>5,
    ),
);
If the above scopes are declared in a 'Post' model, we can perform the following queries:
$posts=Post::model()->published()->findAll();
$posts=Post::model()->published()->recently()->findAll();
$posts=Post::model()->published()->with('comments')->findAll();
Note that the last query is a relational query.

setAttribute() method
public boolean setAttribute(string $name, mixed $value)
$name | string | the attribute name
$value | mixed | the attribute value.
{return} | boolean | whether the attribute exists and the assignment is conducted successfully

Sets the named attribute value. You may also use $this->AttributeName to set the attribute value.

See Also

  • hasAttribute
setIsNewRecord() method
public void setIsNewRecord(boolean $value)
$value boolean whether the record is new and should be inserted when calling save.

See Also

  • getIsNewRecord
setPrimaryKey() method (available since v1.1.0)
public void setPrimaryKey(mixed $value)
$value mixed the new primary key value. If the primary key is composite, the new value should be provided as an array (column name=>column value).

Sets the primary key value. After calling this method, the old primary key value can be obtained from oldPrimaryKey.

tableName() method
public string tableName()
{return} string the table name

Returns the name of the associated database table. By default this method returns the class name as the table name. You may override this method if the table is not named after this convention.

update() method
public boolean update(array $attributes=NULL)
$attributes | array | list of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.
{return} | boolean | whether the update is successful

Updates the row represented by this active record. All loaded attributes will be saved to the database. Note, validation is not performed in this method. You may call validate to perform the validation.

updateAll() method
public integer updateAll(array $attributes, mixed $condition='', array $params=array ( ))
$attributes | array | list of attributes (name=>$value) to be updated
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows being updated

Updates records with the specified condition. See find() for detailed explanation about $condition and $params. Note, the attributes are not checked for safety and no validation is done.

updateByPk() method
public integer updateByPk(mixed $pk, array $attributes, mixed $condition='', array $params=array ( ))
$pk | mixed | primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$attributes | array | list of attributes (name=>$value) to be updated
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows being updated

Updates records with the specified primary key(s). See find() for detailed explanation about $condition and $params. Note, the attributes are not checked for safety and validation is NOT performed.

updateCounters() method
public integer updateCounters(array $counters, mixed $condition='', array $params=array ( ))
$counters | array | the counters to be updated (column name=>increment value)
$condition | mixed | query condition or criteria.
$params | array | parameters to be bound to an SQL statement.
{return} | integer | the number of rows being updated

Updates one or several counter columns. Note, this updates all rows of data unless a condition or criteria is specified. See find() for detailed explanation about $condition and $params.

with() method
public CActiveFinder with()
{return} CActiveFinder the active finder instance. If no parameter is passed in, the object itself will be returned.

Specifies which related objects should be eagerly loaded. This method takes variable number of parameters. Each parameter specifies the name of a relation or child-relation. For example,

// find all posts together with their author and comments
Post::model()->with('author','comments')->findAll();
// find all posts together with their author and the author's profile
Post::model()->with('author','author.profile')->findAll();
The relations should be declared in relations().

By default, the options specified in relations() will be used to do relational query. In order to customize the options on the fly, we should pass an array parameter to the with() method. The array keys are relation names, and the array values are the corresponding query options. For example,
Post::model()->with(array(
    'author'=>array('select'=>'id, name'),
    'comments'=>array('condition'=>'approved=1', 'order'=>'createTime'),
))->findAll();

This method returns a CActiveFinder instance that provides a set of find methods similar to that of CActiveRecord.

Note, the possible parameters to this method have been changed since version 1.0.2. Previously, it was not possible to specify on-th-fly query options, and child-relations were specified as hierarchical arrays.


CActiveRecordBehavior

Package | system.db.ar
Inheritance | class CActiveRecordBehavior » CModelBehavior » CBehavior » CComponent
Implements | IBehavior
Subclasses | CTimestampBehavior
Since | 1.0.2
Version | $Id: CActiveRecordBehavior.php 1678 2010-01-07 21:02:00Z qiang.xue $
CActiveRecordBehavior is the base class for behaviors that can be attached to CActiveRecord. Compared with CModelBehavior, CActiveRecordBehavior attaches to more events that are only defined by CActiveRecord.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
enabled | boolean | whether this behavior is enabled | CBehavior
owner | CComponent | the owner component that this behavior is attached to. | CBehavior

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
afterConstruct() | Responds to CActiveRecord::onAfterConstruct event. | CActiveRecordBehavior
afterDelete() | Responds to CActiveRecord::onAfterDelete event. | CActiveRecordBehavior
afterFind() | Responds to CActiveRecord::onAfterFind event. | CActiveRecordBehavior
afterSave() | Responds to CActiveRecord::onAfterSave event. | CActiveRecordBehavior
afterValidate() | Responds to CModel::onAfterValidate event. | CModelBehavior
asa() | Returns the named behavior object. | CComponent
attach() | Attaches the behavior object to the component. | CBehavior
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beforeDelete() | Responds to CActiveRecord::onBeforeDelete event. | CActiveRecordBehavior
beforeFind() | Responds to CActiveRecord::onBeforeFind event. | CActiveRecordBehavior
beforeSave() | Responds to CActiveRecord::onBeforeSave event. | CActiveRecordBehavior
beforeValidate() | Responds to CModel::onBeforeValidate event. | CModelBehavior
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detach() | Detaches the behavior object from the component. | CBehavior
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
events() | Declares events and the corresponding event handler methods. | CActiveRecordBehavior
getEnabled() |  | CBehavior
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOwner() |  | CBehavior
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setEnabled() |  | CBehavior

Method Details

afterConstruct() method
public void afterConstruct(CEvent $event)
$event CEvent event parameter

Responds to CActiveRecord::onAfterConstruct event. Overrides this method if you want to handle the corresponding event of the owner.

afterDelete() method
public void afterDelete(CEvent $event)
$event CEvent event parameter

Responds to CActiveRecord::onAfterDelete event. Overrides this method if you want to handle the corresponding event of the owner.

afterFind() method
public void afterFind(CEvent $event)
$event CEvent event parameter

Responds to CActiveRecord::onAfterFind event. Overrides this method if you want to handle the corresponding event of the owner.

afterSave() method
public void afterSave(CModelEvent $event)
$event CModelEvent event parameter

Responds to CActiveRecord::onAfterSave event. Overrides this method if you want to handle the corresponding event of the owner.

beforeDelete() method
public void beforeDelete(CEvent $event)
$event CEvent event parameter

Responds to CActiveRecord::onBeforeDelete event. Overrides this method if you want to handle the corresponding event of the owner. You may set CModelEvent::isValid to be false to quit the deletion process.

beforeFind() method (available since v1.0.9)
public void beforeFind(CEvent $event)
$event CEvent event parameter

Responds to CActiveRecord::onBeforeFind event. Overrides this method if you want to handle the corresponding event of the owner.

beforeSave() method
public void beforeSave(CModelEvent $event)
$event CModelEvent event parameter

Responds to CActiveRecord::onBeforeSave event. Overrides this method if you want to handle the corresponding event of the owner. You may set CModelEvent::isValid to be false to quit the saving process.

events() method
public array events()
{return} array events (array keys) and the corresponding event handler methods (array values).

Declares events and the corresponding event handler methods. If you override this method, make sure you merge the parent result to the return value.

See Also

  • CBehavior::events


CActiveRecordMetaData

Package | system.db.ar
Inheritance | class CActiveRecordMetaData
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CActiveRecordMetaData represents the meta-data for an Active Record class.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributeDefaults | array | attribute default values | CActiveRecordMetaData
columns | array | table columns | CActiveRecordMetaData
relations | array | list of relations | CActiveRecordMetaData
tableSchema | CDbTableSchema | the table schema information | CActiveRecordMetaData

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CActiveRecordMetaData

Property Details

attributeDefaults property
public array $attributeDefaults;

attribute default values

columns property
public array $columns;

table columns

relations property
public array $relations;

list of relations

tableSchema property
public CDbTableSchema $tableSchema;

the table schema information

Method Details

__construct() method
public void __construct(CActiveRecord $model)
$model CActiveRecord the model instance

Constructor.


CActiveRelation

Package | system.db.ar
Inheritance | class CActiveRelation » CBaseActiveRelation » CComponent
Subclasses | CBelongsToRelation, CHasManyRelation, CHasOneRelation
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CActiveRelation is the base class for representing active relations that bring back related objects.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias for the table that this relation refers to. | CActiveRelation
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
joinType | string | join type. | CActiveRelation
name | string | name of the related object | CBaseActiveRelation
on | string | ON clause. | CActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation
with | string|array | specifies which related objects should be eagerly loaded when this related object is lazily loaded. | CActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CActiveRelation
raiseEvent() | Raises an event. | CComponent

Property Details

alias property (available since v1.0.1)
public string $alias;

the alias for the table that this relation refers to. Defaults to null, meaning the alias will be the same as the relation name.

joinType property
public string $joinType;

join type. Defaults to 'LEFT OUTER JOIN'.

on property (available since v1.0.2)
public string $on;

ON clause. The condition specified here will be appended to the joining condition using AND operator.

with property
public string|array $with;

specifies which related objects should be eagerly loaded when this related object is lazily loaded. For more details about this property, see CActiveRecord::with().

Method Details

mergeWith() method (available since v1.0.5)
public void mergeWith(array $criteria)
$criteria array the dynamically specified criteria

Merges this relation with a criteria specified dynamically.


CBaseActiveRelation

Package | system.db.ar
Inheritance | class CBaseActiveRelation » CComponent
Subclasses | CActiveRelation, CStatRelation
Since | 1.0.4
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CBaseActiveRelation is the base class for all active relations.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
name | string | name of the related object | CBaseActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CBaseActiveRelation
raiseEvent() | Raises an event. | CComponent

Property Details

className property
public string $className;

name of the related active record class

condition property
public string $condition;

WHERE clause. For CActiveRelation descendant classes, column names referenced in the condition should be disambiguated with prefix '??.'.

foreignKey property
public string $foreignKey;

the foreign key in this relation

group property
public string $group;

GROUP BY clause. For CActiveRelation descendant classes, column names referenced in this property should be disambiguated with prefix '??.'.

having property
public string $having;

HAVING clause. For CActiveRelation descendant classes, column names referenced in this property should be disambiguated with prefix '??.'.

name property
public string $name;

name of the related object

order property
public string $order;

ORDER BY clause. For CActiveRelation descendant classes, column names referenced in this property should be disambiguated with prefix '??.'.

params property
public array $params;

the parameters that are to be bound to the condition. The keys are parameter placeholder names, and the values are parameter values.

select property
public mixed $select;

list of column names (an array, or a string of names separated by commas) to be selected. Do not quote or prefix the column names unless they are used in an expression. In that case, you should prefix the column names with '??.'.

Method Details

__construct() method
public void __construct(string $name, string $className, string $foreignKey, array $options=array ( ))
$name | string | name of the relation
$className | string | name of the related active record class
$foreignKey | string | foreign key for this relation
$options | array | additional options (name=>value). The keys must be the property names of this class.

Constructor.

mergeWith() method (available since v1.0.5)
public void mergeWith(array $criteria)
$criteria array the dynamically specified criteria

Merges this relation with a criteria specified dynamically.


CBelongsToRelation

Package | system.db.ar
Inheritance | class CBelongsToRelation » CActiveRelation » CBaseActiveRelation » CComponent
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CBelongsToRelation represents the parameters specifying a BELONGS_TO relation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias for the table that this relation refers to. | CActiveRelation
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
joinType | string | join type. | CActiveRelation
name | string | name of the related object | CBaseActiveRelation
on | string | ON clause. | CActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation
with | string|array | specifies which related objects should be eagerly loaded when this related object is lazily loaded. | CActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CActiveRelation
raiseEvent() | Raises an event. | CComponent


CHasManyRelation

Package | system.db.ar
Inheritance | class CHasManyRelation » CActiveRelation » CBaseActiveRelation » CComponent
Subclasses | CManyManyRelation
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CHasManyRelation represents the parameters specifying a HAS_MANY relation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias for the table that this relation refers to. | CActiveRelation
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
index | string | the name of the column that should be used as the key for storing related objects. | CHasManyRelation
joinType | string | join type. | CActiveRelation
limit | integer | limit of the rows to be selected. | CHasManyRelation
name | string | name of the related object | CBaseActiveRelation
offset | integer | offset of the rows to be selected. | CHasManyRelation
on | string | ON clause. | CActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation
together | boolean | whether this table should be joined with the primary table. | CHasManyRelation
with | string|array | specifies which related objects should be eagerly loaded when this related object is lazily loaded. | CActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CHasManyRelation
raiseEvent() | Raises an event. | CComponent

Property Details

index property (available since v1.0.7)
public string $index;

the name of the column that should be used as the key for storing related objects. Defaults to null, meaning using zero-based integer IDs.

limit property
public integer $limit;

limit of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no limit.

offset property
public integer $offset;

offset of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no offset.

together property
public boolean $together;

whether this table should be joined with the primary table. When setting this property to be false, the table associated with this relation will appear in a separate JOIN statement. Defaults to true, meaning the table will be joined together with the primary table. Note that in version 1.0.x, the default value of this property was false.

Method Details

mergeWith() method (available since v1.0.5)
public void mergeWith(array $criteria)
$criteria array the dynamically specified criteria

Merges this relation with a criteria specified dynamically.


CHasOneRelation

Package | system.db.ar
Inheritance | class CHasOneRelation » CActiveRelation » CBaseActiveRelation » CComponent
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CHasOneRelation represents the parameters specifying a HAS_ONE relation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias for the table that this relation refers to. | CActiveRelation
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
joinType | string | join type. | CActiveRelation
name | string | name of the related object | CBaseActiveRelation
on | string | ON clause. | CActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation
with | string|array | specifies which related objects should be eagerly loaded when this related object is lazily loaded. | CActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CActiveRelation
raiseEvent() | Raises an event. | CComponent


CJoinElement

Package | system.db.ar
Inheritance | class CJoinElement
Since | 1.0
Version | $Id: CActiveFinder.php 1869 2010-03-09 22:02:12Z qiang.xue $
CJoinElement represents a tree node in the join tree created by CActiveFinder.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
children | array | list of child join elements | CJoinElement
id | integer | the unique ID of this tree node | CJoinElement
model | CActiveRecord | the model associated with this tree node | CJoinElement
rawTableAlias | string | the quoted table alias for this element | CJoinElement
records | array | list of active records found by the queries. | CJoinElement
relation | CActiveRelation | the relation represented by this tree node | CJoinElement
stats | array | list of stat elements | CJoinElement
tableAlias | string | table alias for this join element | CJoinElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CJoinElement
afterFind() | Calls CActiveRecord::afterFind of all the records. | CJoinElement
beforeFind() | Calls CActiveRecord::beforeFind. | CJoinElement
buildQuery() | Builds the join query with all descendant HAS_ONE and BELONGS_TO nodes. | CJoinElement
count() | Count the number of primary records returned by the join statement. | CJoinElement
find() | Performs the recursive finding with the criteria. | CJoinElement
findWithBase() | Performs the eager loading with the base records ready. | CJoinElement
getColumnPrefix() |  | CJoinElement
getColumnSelect() | Generates the list of columns to be selected. | CJoinElement
getJoinCondition() |  | CJoinElement
getPrimaryKeyRange() |  | CJoinElement
getPrimaryKeySelect() |  | CJoinElement
getTableNameWithAlias() |  | CJoinElement
lazyFind() | Performs lazy find with the specified base record. | CJoinElement
runQuery() | Executes the join query and populates the query results. | CJoinElement

Property Details

children property
public array $children;

list of child join elements

id property
public integer $id;

the unique ID of this tree node

model property
public CActiveRecord $model;

the model associated with this tree node

rawTableAlias property
public string $rawTableAlias;

the quoted table alias for this element

records property
public array $records;

list of active records found by the queries. They are indexed by primary key values.

relation property
public CActiveRelation $relation;

the relation represented by this tree node

stats property (available since v1.0.4)
public array $stats;

list of stat elements

tableAlias property
public string $tableAlias;

table alias for this join element

Method Details

__construct() method
public void __construct(CActiveFinder $finder, mixed $relation, CJoinElement $parent=NULL, integer $id=0)
$finder | CActiveFinder | the finder
$relation | mixed | the relation (if the third parameter is not null) or the model (if the third parameter is null) associated with this tree node.
$parent | CJoinElement | the parent tree node
$id | integer | the ID of this tree node that is unique among all the tree nodes

Constructor.

afterFind() method (available since v1.0.3)
public void afterFind()

Calls CActiveRecord::afterFind of all the records.

beforeFind() method (available since v1.0.11)
public void beforeFind()

Calls CActiveRecord::beforeFind.

buildQuery() method
public void buildQuery(CJoinQuery $query)
$query CJoinQuery the query being built up

Builds the join query with all descendant HAS_ONE and BELONGS_TO nodes.

count() method (available since v1.0.3)
public integer count(CDbCriteria $criteria=NULL)
$criteria | CDbCriteria | the query criteria
{return} | integer | number of primary records.

Count the number of primary records returned by the join statement.

find() method
public void find(CDbCriteria $criteria=NULL)
$criteria CDbCriteria the query criteria

Performs the recursive finding with the criteria.

findWithBase() method
public void findWithBase(mixed $baseRecords)
$baseRecords mixed the available base record(s).

Performs the eager loading with the base records ready.

getColumnPrefix() method
public string getColumnPrefix()
{return} string the column prefix for column reference disambiguation

getColumnSelect() method
public string getColumnSelect(mixed $select='*')
$select | mixed | columns to be selected. Defaults to '*', indicating all columns.
{return} | string | the column selection

Generates the list of columns to be selected. Columns will be properly aliased and primary keys will be added to selection if they are not specified.

getJoinCondition() method
public string getJoinCondition()
{return} string the join statement (this node joins with its parent)

getPrimaryKeyRange() method
public string getPrimaryKeyRange()
{return} string the condition that specifies only the rows with the selected primary key values.

getPrimaryKeySelect() method
public string getPrimaryKeySelect()
{return} string the primary key selection

getTableNameWithAlias() method
public string getTableNameWithAlias()
{return} string the table name and the table alias (if any). This can be used directly in SQL query without escaping.

lazyFind() method
public void lazyFind(CActiveRecord $baseRecord)
$baseRecord CActiveRecord the active record whose related object is to be fetched.

Performs lazy find with the specified base record.

runQuery() method
public void runQuery(CJoinQuery $query)
$query CJoinQuery the query to be executed.

Executes the join query and populates the query results.


CJoinQuery

Package | system.db.ar
Inheritance | class CJoinQuery
Since | 1.0
Version | $Id: CActiveFinder.php 1869 2010-03-09 22:02:12Z qiang.xue $
CJoinQuery represents a JOIN SQL statement.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
conditions | array | list of WHERE clauses | CJoinQuery
distinct | boolean | whether to select distinct result set | CJoinQuery
elements | array | list of join element IDs (id=>true) | CJoinQuery
groups | array | list of GROUP BY clauses | CJoinQuery
havings | array | list of HAVING clauses | CJoinQuery
joins | array | list of join statement | CJoinQuery
limit | integer | row limit | CJoinQuery
offset | integer | row offset | CJoinQuery
orders | array | list of ORDER BY clauses | CJoinQuery
params | array | list of query parameters | CJoinQuery
selects | array | list of column selections | CJoinQuery

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CJoinQuery
createCommand() | Creates the SQL statement. | CJoinQuery
join() | Joins with another join element | CJoinQuery

Property Details

conditions property
public array $conditions;

list of WHERE clauses

distinct property (available since v1.0.9)
public boolean $distinct;

whether to select distinct result set

elements property
public array $elements;

list of join element IDs (id=>true)

groups property
public array $groups;

list of GROUP BY clauses

havings property
public array $havings;

list of HAVING clauses

joins property
public array $joins;

list of join statement

limit property
public integer $limit;

row limit

offset property
public integer $offset;

row offset

orders property
public array $orders;

list of ORDER BY clauses

params property
public array $params;

list of query parameters

selects property
public array $selects;

list of column selections

Method Details

__construct() method
public void __construct(CJoinElement $joinElement, CDbCriteria $criteria=NULL)
$joinElement | CJoinElement | The root join tree.
$criteria | CDbCriteria | the query criteria

Constructor.

createCommand() method
public string createCommand(CDbCommandBuilder $builder)
$builder | CDbCommandBuilder | the command builder
{return} | string | the SQL statement

Creates the SQL statement.

join() method
public void join(CJoinElement $element)
$element CJoinElement the element to be joined

Joins with another join element


CManyManyRelation

Package | system.db.ar
Inheritance | class CManyManyRelation » CHasManyRelation » CActiveRelation » CBaseActiveRelation » CComponent
Since | 1.0
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CManyManyRelation represents the parameters specifying a MANY_MANY relation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias for the table that this relation refers to. | CActiveRelation
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
index | string | the name of the column that should be used as the key for storing related objects. | CHasManyRelation
joinType | string | join type. | CActiveRelation
limit | integer | limit of the rows to be selected. | CHasManyRelation
name | string | name of the related object | CBaseActiveRelation
offset | integer | offset of the rows to be selected. | CHasManyRelation
on | string | ON clause. | CActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | mixed | list of column names (an array, or a string of names separated by commas) to be selected. | CBaseActiveRelation
together | boolean | whether this table should be joined with the primary table. | CHasManyRelation
with | string|array | specifies which related objects should be eagerly loaded when this related object is lazily loaded. | CActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CHasManyRelation
raiseEvent() | Raises an event. | CComponent


CStatElement

Package | system.db.ar
Inheritance | class CStatElement
Since | 1.0.4
Version | $Id: CActiveFinder.php 1869 2010-03-09 22:02:12Z qiang.xue $
CStatElement represents STAT join element for CActiveFinder.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
relation | CActiveRelation | the relation represented by this tree node | CStatElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CStatElement
query() | Performs the STAT query. | CStatElement

Property Details

relation property
public CActiveRelation $relation;

the relation represented by this tree node

Method Details

__construct() method
public void __construct(CActiveFinder $finder, CStatRelation $relation, CJoinElement $parent)
$finder | CActiveFinder | the finder
$relation | CStatRelation | the STAT relation
$parent | CJoinElement | the join element owning this STAT element

Constructor.

query() method
public void query()

Performs the STAT query.


CStatRelation

Package | system.db.ar
Inheritance | class CStatRelation » CBaseActiveRelation » CComponent
Since | 1.0.4
Version | $Id: CActiveRecord.php 1893 2010-03-13 01:00:47Z qiang.xue $
CStatRelation represents a statistical relational query.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
className | string | name of the related active record class | CBaseActiveRelation
condition | string | WHERE clause. | CBaseActiveRelation
defaultValue | mixed | the default value to be assigned to those records that do not receive a statistical query result. | CStatRelation
foreignKey | string | the foreign key in this relation | CBaseActiveRelation
group | string | GROUP BY clause. | CBaseActiveRelation
having | string | HAVING clause. | CBaseActiveRelation
name | string | name of the related object | CBaseActiveRelation
order | string | ORDER BY clause. | CBaseActiveRelation
params | array | the parameters that are to be bound to the condition. | CBaseActiveRelation
select | string | the statistical expression. | CBaseActiveRelation

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CBaseActiveRelation
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
mergeWith() | Merges this relation with a criteria specified dynamically. | CStatRelation
raiseEvent() | Raises an event. | CComponent

Property Details

defaultValue property
public mixed $defaultValue;

the default value to be assigned to those records that do not receive a statistical query result. Defaults to 0.

Method Details

mergeWith() method (available since v1.0.5)
public void mergeWith(array $criteria)
$criteria array the dynamically specified criteria

Merges this relation with a criteria specified dynamically.


CDbColumnSchema

Package | system.db.schema
Inheritance | class CDbColumnSchema » CComponent
Subclasses | CMssqlColumnSchema, CMysqlColumnSchema, COciColumnSchema, CPgsqlColumnSchema, CSqliteColumnSchema
Since | 1.0
Version | $Id: CDbColumnSchema.php 1830 2010-02-20 03:07:45Z qiang.xue $
CDbColumnSchema class describes the column meta data of a database table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() | Extracts the default value for the column. | CDbColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CDbColumnSchema
extractType() | Extracts the PHP type from DB type. | CDbColumnSchema

Property Details

allowNull property
public boolean $allowNull;

whether this column can be null.

dbType property
public string $dbType;

the DB type of this column.

defaultValue property
public mixed $defaultValue;

default value of this column

isForeignKey property
public boolean $isForeignKey;

whether this column is a foreign key

isPrimaryKey property
public boolean $isPrimaryKey;

whether this column is a primary key

name property
public string $name;

name of this column (without quotes).

precision property
public integer $precision;

precision of the column data, if it is numeric.

rawName property
public string $rawName;

raw name of this column. This is the quoted name that can be used in SQL queries.

scale property
public integer $scale;

scale of the column data, if it is numeric.

size property
public integer $size;

size of the column.

type property
public string $type;

the PHP type of this column.

Method Details

extractDefault() method
protected void extractDefault(mixed $defaultValue)
$defaultValue mixed the default value obtained from metadata

Extracts the default value for the column. The value is typecasted to correct PHP type.

extractLimit() method
protected void extractLimit(string $dbType)
$dbType string the column's DB type

Extracts size, precision and scale information from column's DB type.

extractType() method
protected void extractType(string $dbType)
$dbType string DB type

Extracts the PHP type from DB type.

init() method
public void init(string $dbType, mixed $defaultValue)
$dbType | string | the column's DB type
$defaultValue | mixed | the default value

Initializes the column with its DB type and default value. This sets up the column's PHP type, size, precision, scale as well as default value.

typecast() method
public mixed typecast(mixed $value)
$value | mixed | input value
{return} | mixed | converted value

Converts the input value to the type that this column is of.


CDbCommandBuilder

Package | system.db.schema
Inheritance | class CDbCommandBuilder » CComponent
Subclasses | CMssqlCommandBuilder, COciCommandBuilder, CSqliteCommandBuilder
Since | 1.0
Version | $Id: CDbCommandBuilder.php 1814 2010-02-18 21:47:00Z qiang.xue $
CDbCommandBuilder provides basic methods to create query commands for tables.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | database connection. | CDbCommandBuilder
schema | CDbSchema | the schema for this command builder. | CDbCommandBuilder

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CDbCommandBuilder
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyCondition() | Alters the SQL to apply WHERE clause. | CDbCommandBuilder
applyGroup() | Alters the SQL to apply GROUP BY. | CDbCommandBuilder
applyHaving() | Alters the SQL to apply HAVING. | CDbCommandBuilder
applyJoin() | Alters the SQL to apply JOIN clause. | CDbCommandBuilder
applyLimit() | Alters the SQL to apply LIMIT and OFFSET. | CDbCommandBuilder
applyOrder() | Alters the SQL to apply ORDER BY. | CDbCommandBuilder
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindValues() | Binds parameter values for an SQL command. | CDbCommandBuilder
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createColumnCriteria() | Creates a query criteria with the specified column values. | CDbCommandBuilder
createCountCommand() | Creates a COUNT(*) command for a single table. | CDbCommandBuilder
createCriteria() | Creates a query criteria. | CDbCommandBuilder
createDeleteCommand() | Creates a DELETE command. | CDbCommandBuilder
createFindCommand() | Creates a SELECT command for a single table. | CDbCommandBuilder
createInCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createInsertCommand() | Creates an INSERT command. | CDbCommandBuilder
createPkCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createPkCriteria() | Creates a query criteria with the specified primary key. | CDbCommandBuilder
createSearchCondition() | Generates the expression for searching the specified keywords within a list of columns. | CDbCommandBuilder
createSqlCommand() | Creates a command based on a given SQL statement. | CDbCommandBuilder
createUpdateCommand() | Creates an UPDATE command. | CDbCommandBuilder
createUpdateCounterCommand() | Creates an UPDATE command that increments/decrements certain columns. | CDbCommandBuilder
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDbConnection() |  | CDbCommandBuilder
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLastInsertID() | Returns the last insertion ID for the specified table. | CDbCommandBuilder
getSchema() |  | CDbCommandBuilder
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCompositeInCondition() | Generates the expression for selecting rows with specified composite key values. | CDbCommandBuilder
ensureTable() | Checks if the parameter is a valid table schema. | CDbCommandBuilder

Property Details

dbConnection property read-only
public CDbConnection getDbConnection()

database connection.

schema property read-only
public CDbSchema getSchema()

the schema for this command builder.

Method Details

__construct() method
public void __construct(CDbSchema $schema)
$schema CDbSchema the schema for this command builder

applyCondition() method
public string applyCondition(string $sql, string $condition)
$sql | string | the SQL statement without WHERE clause
$condition | string | the WHERE clause (without WHERE keyword)
{return} | string | the altered SQL statement

Alters the SQL to apply WHERE clause.

applyGroup() method
public string applyGroup(string $sql, string $group)
$sql | string | SQL query string without GROUP BY.
$group | string | GROUP BY
{return} | string | SQL with GROUP BY.

Alters the SQL to apply GROUP BY.

applyHaving() method (available since v1.0.1)
public string applyHaving(string $sql, string $having)
$sql | string | SQL query string without HAVING
$having | string | HAVING
{return} | string | SQL with HAVING

Alters the SQL to apply HAVING.

applyJoin() method
public string applyJoin(string $sql, string $join)
$sql | string | the SQL statement to be altered
$join | string | the JOIN clause (starting with join type, such as INNER JOIN)
{return} | string | the altered SQL statement

Alters the SQL to apply JOIN clause.

applyLimit() method
public string applyLimit(string $sql, integer $limit, integer $offset)
$sql | string | SQL query string without LIMIT and OFFSET.
$limit | integer | maximum number of rows, -1 to ignore limit.
$offset | integer | row offset, -1 to ignore offset.
{return} | string | SQL with LIMIT and OFFSET

Alters the SQL to apply LIMIT and OFFSET. Default implementation is applicable for PostgreSQL, MySQL and SQLite.

applyOrder() method
public string applyOrder(string $sql, string $orderBy)
$sql | string | SQL statement without ORDER BY.
$orderBy | string | column ordering
{return} | string | modified SQL applied with ORDER BY.

Alters the SQL to apply ORDER BY.

bindValues() method
public void bindValues(CDbCommand $command, array $values)
$command | CDbCommand | database command
$values | array | values for binding (integer-indexed array for question mark placeholders, string-indexed array for named placeholders)

Binds parameter values for an SQL command.

createColumnCriteria() method
public CDbCriteria createColumnCriteria(mixed $table, array $columns, mixed $condition='', array $params=array ( ), string $prefix=NULL)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$columns | array | column values that should be matched in the query (name=>value)
$condition | mixed | query condition or criteria. If a string, it is treated as query condition; If an array, it is treated as the initial values for constructing a CDbCriteria; Otherwise, it should be an instance of CDbCriteria.
$params | array | parameters to be bound to an SQL statement. This is only used when the second parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
$prefix | string | column prefix (ended with dot). If null, it will be the table name
{return} | CDbCriteria | the created query criteria

Creates a query criteria with the specified column values.

createCompositeInCondition() method (available since v1.0.4)
protected string createCompositeInCondition(CDbTableSchema $table, array $values, string $prefix)
$table | CDbTableSchema | the table schema
$values | array | list of primary key values to be selected within
$prefix | string | column prefix (ended with dot)
{return} | string | the expression for selection

Generates the expression for selecting rows with specified composite key values.

createCountCommand() method
public CDbCommand createCountCommand(mixed $table, CDbCriteria $criteria, string $alias='t')
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$criteria | CDbCriteria | the query criteria
$alias | string | the alias name of the primary table. Defaults to 't'.
{return} | CDbCommand | query command.

Creates a COUNT(*) command for a single table.

createCriteria() method
public CDbCriteria createCriteria(mixed $condition='', mixed $params=array ( ))
$condition | mixed | the table schema (CDbTableSchema) or the table name (string).
$params | mixed | query condition or criteria. If a string, it is treated as query condition (the WHERE clause); If an array, it is treated as the initial values for constructing a CDbCriteria object; Otherwise, it should be an instance of CDbCriteria.
{return} | CDbCriteria | the created query criteria

Creates a query criteria.

createDeleteCommand() method
public CDbCommand createDeleteCommand(mixed $table, CDbCriteria $criteria)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$criteria | CDbCriteria | the query criteria
{return} | CDbCommand | delete command.

Creates a DELETE command.

createFindCommand() method
public CDbCommand createFindCommand(mixed $table, CDbCriteria $criteria, string $alias='t')
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$criteria | CDbCriteria | the query criteria
$alias | string | the alias name of the primary table. Defaults to 't'.
{return} | CDbCommand | query command.

Creates a SELECT command for a single table.

createInCondition() method (available since v1.0.4)
public string createInCondition(mixed $table, mixed $columnName, array $values, string $prefix=NULL)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$columnName | mixed | the column name(s). It can be either a string indicating a single column or an array of column names. If the latter, it stands for a composite key.
$values | array | list of key values to be selected within
$prefix | string | column prefix (ended with dot). If null, it will be the table name
{return} | string | the expression for selection

Generates the expression for selecting rows of specified primary key values.

createInsertCommand() method
public CDbCommand createInsertCommand(mixed $table, array $data)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$data | array | data to be inserted (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
{return} | CDbCommand | insert command

Creates an INSERT command.

createPkCondition() method
public string createPkCondition(mixed $table, array $values, string $prefix=NULL)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$values | array | list of primary key values to be selected within
$prefix | string | column prefix (ended with dot). If null, it will be the table name
{return} | string | the expression for selection

Generates the expression for selecting rows of specified primary key values.

createPkCriteria() method
public CDbCriteria createPkCriteria(mixed $table, mixed $pk, mixed $condition='', array $params=array ( ), string $prefix=NULL)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$pk | mixed | primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$condition | mixed | query condition or criteria. If a string, it is treated as query condition; If an array, it is treated as the initial values for constructing a CDbCriteria; Otherwise, it should be an instance of CDbCriteria.
$params | array | parameters to be bound to an SQL statement. This is only used when the second parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
$prefix | string | column prefix (ended with dot). If null, it will be the table name
{return} | CDbCriteria | the created query criteria

Creates a query criteria with the specified primary key.

createSearchCondition() method
public string createSearchCondition(mixed $table, array $columns, mixed $keywords, string $prefix=NULL, boolean $caseSensitive=true)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$columns | array | list of column names for potential search condition.
$keywords | mixed | search keywords. This can be either a string with space-separated keywords or an array of keywords.
$prefix | string | optional column prefix (with dot at the end). If null, the table name will be used as the prefix.
$caseSensitive | boolean | whether the search is case-sensitive. Defaults to true. This parameter has been available since version 1.0.4.
{return} | string | SQL search condition matching on a set of columns. An empty string is returned if either the column array or the keywords are empty.

Generates the expression for searching the specified keywords within a list of columns. The search expression is generated using the 'LIKE' SQL syntax. Every word in the keywords must be present and appear in at least one of the columns.

createSqlCommand() method
public CDbCommand createSqlCommand(string $sql, array $params=array ( ))
$sql | string | the explicitly specified SQL statement
$params | array | parameters that will be bound to the SQL statement
{return} | CDbCommand | the created command

Creates a command based on a given SQL statement.

createUpdateCommand() method
public CDbCommand createUpdateCommand(mixed $table, array $data, CDbCriteria $criteria)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$data | array | list of columns to be updated (name=>value)
$criteria | CDbCriteria | the query criteria
{return} | CDbCommand | update command.

Creates an UPDATE command.

createUpdateCounterCommand() method
public CDbCommand createUpdateCounterCommand(mixed $table, CDbCriteria $counters, array $criteria)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$counters | CDbCriteria | the query criteria
$criteria | array | counters to be updated (counter increments/decrements indexed by column names.)
{return} | CDbCommand | the created command

Creates an UPDATE command that increments/decrements certain columns.

ensureTable() method (available since v1.0.4)
protected void ensureTable(mixed $table)
$table mixed table schema (CDbTableSchema) or table name (string). If this refers to a valid table name, this parameter will be returned with the corresponding table schema.

Checks if the parameter is a valid table schema. If it is a string, the corresponding table schema will be retrieved.

getDbConnection() method
public CDbConnection getDbConnection()
{return} CDbConnection database connection.

getLastInsertID() method
public mixed getLastInsertID(mixed $table)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
{return} | mixed | last insertion id. Null is returned if no sequence name.

Returns the last insertion ID for the specified table.

getSchema() method
public CDbSchema getSchema()
{return} CDbSchema the schema for this command builder.


CDbCriteria

Package | system.db.schema
Inheritance | class CDbCriteria
Since | 1.0
Version | $Id: CDbCriteria.php 1896 2010-03-13 14:11:24Z qiang.xue $
CDbCriteria represents a query criteria, such as conditions, ordering by, limit/offset.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
alias | string | the alias name of the table. | CDbCriteria
condition | string | query condition. | CDbCriteria
distinct | boolean | whether to select distinct rows of data only. | CDbCriteria
group | string | how to group the query results. | CDbCriteria
having | string | the condition to be applied with GROUP-BY clause. | CDbCriteria
join | string | how to join with other tables. | CDbCriteria
limit | integer | maximum number of records to be returned. | CDbCriteria
offset | integer | zero-based offset from where the records are to be returned. | CDbCriteria
order | string | how to sort the query results. | CDbCriteria
params | array | list of query parameter values indexed by parameter placeholders. | CDbCriteria
select | mixed | the columns being selected. | CDbCriteria
with | array | the relational query criteria. | CDbCriteria

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CDbCriteria
addColumnCondition() | Appends a condition for matching the given list of column values. | CDbCriteria
addCondition() | Appends a condition to the existing condition. | CDbCriteria
addInCondition() | Appends an IN condition to the existing condition. | CDbCriteria
addNotInCondition() | Appends an NOT IN condition to the existing condition. | CDbCriteria
addSearchCondition() | Appends a search condition to the existing condition. | CDbCriteria
compare() | Adds a comparison expression to the condition property. | CDbCriteria
mergeWith() | Merges with another criteria. | CDbCriteria
toArray() |  | CDbCriteria

Property Details

alias property
public string $alias;

the alias name of the table. If not set, it means the alias is 't'.

condition property
public string $condition;

query condition. This refers to the WHERE clause in an SQL statement. For example, age>31 AND team=1.

distinct property (available since v1.0.9)
public boolean $distinct;

whether to select distinct rows of data only. If this is set true, the SELECT clause would be changed to SELECT DISTINCT.

group property
public string $group;

how to group the query results. This refers to the GROUP BY clause in an SQL statement. For example, 'projectID, teamID'.

having property (available since v1.0.1)
public string $having;

the condition to be applied with GROUP-BY clause. For example, 'SUM(revenue)<50000'.

join property
public string $join;

how to join with other tables. This refers to the JOIN clause in an SQL statement. For example, 'LEFT JOIN users ON users.id=authorID'.

limit property
public integer $limit;

maximum number of records to be returned. If less than 0, it means no limit.

offset property
public integer $offset;

zero-based offset from where the records are to be returned. If less than 0, it means starting from the beginning.

order property
public string $order;

how to sort the query results. This refers to the ORDER BY clause in an SQL statement.

params property
public array $params;

list of query parameter values indexed by parameter placeholders. For example, array(':name'=>'Dan', ':age'=>31).

select property
public mixed $select;

the columns being selected. This refers to the SELECT clause in an SQL statement. The property can be either a string (column names separated by commas) or an array of column names. Defaults to '*', meaning all columns.

with property (available since v1.1.0)
public array $with;

the relational query criteria. This is used for fetching related objects in eager loading fashion. This property is effective only when the criteria is passed as a parameter to the following methods of CActiveRecord:

  • CActiveRecord::find()
  • CActiveRecord::findAll()
  • CActiveRecord::findByPk()
  • CActiveRecord::findAllByPk()
  • CActiveRecord::findByAttributes()
  • CActiveRecord::findAllByAttributes()
  • CActiveRecord::count()
The property value will be used as the parameter to the CActiveRecord::with() method to perform the eager loading. Please refer to CActiveRecord::with() on how to specify this parameter.

Method Details

__construct() method
public void __construct(array $data=array ( ))
$data array criteria initial property values (indexed by property name)

Constructor.

addColumnCondition() method (available since v1.0.10)
public CDbCriteria addColumnCondition(array $columns, string $columnOperator='AND', string $operator='AND')
$columns | array | list of column names and values to be matched (name=>value)
$columnOperator | string | the operator to concatenate multiple column matching condition. Defaults to 'AND'.
$operator | string | the operator used to concatenate the new condition with the existing one. Defaults to 'AND'.
{return} | CDbCriteria | the criteria object itself

Appends a condition for matching the given list of column values. The generated condition will be concatenated to the existing condition via the specified operator which defaults to 'AND'. The condition is generated by matching each column and the corresponding value.

addCondition() method (available since v1.0.9)
public CDbCriteria addCondition(mixed $condition, string $operator='AND')
$condition | mixed | the new condition. It can be either a string or an array of strings.
$operator | string | the operator to join different conditions. Defaults to 'AND'.
{return} | CDbCriteria | the criteria object itself

Appends a condition to the existing condition. The new condition and the existing condition will be concatenated via the specified operator which defaults to 'AND'. The new condition can also be an array. In this case, all elements in the array will be concatenated together via the operator. This method handles the case when the existing condition is empty. After calling this method, the condition property will be modified.

addInCondition() method (available since v1.0.10)
public CDbCriteria addInCondition(string $column, array $values, string $operator='AND')
$column | string | the column name (or a valid SQL expression)
$values | array | list of values that the column value should be in
$operator | string | the operator used to concatenate the new condition with the existing one. Defaults to 'AND'.
{return} | CDbCriteria | the criteria object itself

Appends an IN condition to the existing condition. The IN condition and the existing condition will be concatenated via the specified operator which defaults to 'AND'. The IN condition is generated by using the SQL IN operator which requires the specified column value to be among the given list of values.

addNotInCondition() method (available since v1.1.1)
public CDbCriteria addNotInCondition(string $column, array $values, string $operator='AND')
$column | string | the column name (or a valid SQL expression)
$values | array | list of values that the column value should be in
$operator | string | the operator used to concatenate the new condition with the existing one. Defaults to 'AND'.
{return} | CDbCriteria | the criteria object itself

Appends an NOT IN condition to the existing condition. The NOT IN condition and the existing condition will be concatenated via the specified operator which defaults to 'AND'. The NOT IN condition is generated by using the SQL NOT IN operator which requires the specified column value to be among the given list of values.

addSearchCondition() method (available since v1.0.10)
public CDbCriteria addSearchCondition(string $column, string $keyword, boolean $escape=true, string $operator='AND', string $like='LIKE')
$column | string | the column name (or a valid SQL expression)
$keyword | string | the search keyword. This interpretation of the keyword is affected by the next parameter.
$escape | boolean | whether the keyword should be escaped if it contains characters % or _. When this parameter is true (default), the special characters % (matches 0 or more characters) and _ (matches a single character) will be escaped, and the keyword will be surrounded with a % character on both ends. When this parameter is false, the keyword will be directly used for matching without any change.
$operator | string | the operator used to concatenate the new condition with the existing one. Defaults to 'AND'.
$like | string | the LIKE operator. Defaults to 'LIKE'. You may also set this to be 'NOT LIKE'.
{return} | CDbCriteria | the criteria object itself

Appends a search condition to the existing condition. The search condition and the existing condition will be concatenated via the specified operator which defaults to 'AND'. The search condition is generated using the SQL LIKE operator with the given column name and search keyword.

compare() method (available since v1.1.1)
public CDbCriteria compare(string $column, mixed $value, boolean $partialMatch=false, string $operator='AND')
$column | string | the name of the column to be searched
$value | mixed | the column value to be compared with. If the value is a string, the aforementioned intelligent comparison will be conducted. If the value is an array, the comparison is done by exact match of any of the value in the array. If the string or the array is empty, the existing search condition will not be modified.
$partialMatch | boolean | whether the value should consider partial text match (using LIKE and NOT LIKE operators). Defaults to false, meaning exact comparison.
$operator | string | the operator used to concatenate the new condition with the existing one. Defaults to 'AND'.
{return} | CDbCriteria | the criteria object itself

Adds a comparison expression to the condition property.

This method is a helper that appends to the condition property with a new comparison expression. The comparison is done by comparing a column with the given value using some comparison operator.

The comparison operator is intelligently determined based on the first few characters in the given value. In particular, it recognizes the following operators if they appear as the leading characters in the given value:

  • <: the column must be less than the given value.
  • >: the column must be greater than the given value.
  • <=: the column must be less than or equal to the given value.
  • >=: the column must be greater than or equal to the given value.
  • <>: the column must not be the same as the given value. Note that when $partialMatch is true, this would mean the value must not be a substring of the column.
  • =: the column must be equal to the given value.
  • none of the above: the column must be equal to the given value. Note that when $partialMatch is true, this would mean the value must be the same as the given value or be a substring of it.

Note that any surrounding white spaces will be removed from the value before comparison. When the value is empty, no comparison expression will be added to the search condition.

mergeWith() method (available since v1.0.5)
public void mergeWith(CDbCriteria $criteria, boolean $useAnd=true)
$criteria | CDbCriteria | the criteria to be merged with.
$useAnd | boolean | whether to use 'AND' to merge condition and having options. If false, 'OR' will be used instead. Defaults to 'AND'. This parameter has been available since version 1.0.6.

Merges with another criteria. In general, the merging makes the resulting criteria more restrictive. For example, if both criterias have conditions, they will be 'AND' together. Also, the criteria passed as the parameter takes precedence in case two options cannot be merged (e.g. LIMIT, OFFSET).

toArray() method (available since v1.0.6)
public array toArray()
{return} array the array representation of the criteria


CDbExpression

Package | system.db.schema
Inheritance | class CDbExpression » CComponent
Since | 1.0.2
Version | $Id: CDbExpression.php 1787 2010-02-01 23:02:40Z qiang.xue $
CDbExpression represents a DB expression that does not need escaping. CDbExpression is mainly used in CActiveRecord as attribute values. When inserting or updating a CActiveRecord, attribute values of type CDbExpression will be directly put into the corresponding SQL statement without escaping. A typical usage is that an attribute is set with 'NOW()' expression so that saving the record would fill the corresponding column with the current DB server timestamp.

Starting from version 1.1.1, one can also specify parameters to be bound for the expression. For example, if the expression is 'LOWER(:value)', then one can set params to be array(':value'=>$value).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
expression | string | the DB expression | CDbExpression
params | array | list of parameters that should be bound for this expression. | CDbExpression

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbExpression
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__toString() | String magic method | CDbExpression
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

expression property
public string $expression;

the DB expression

params property (available since v1.1.1)
public array $params;

list of parameters that should be bound for this expression. The keys are placeholders appearing in expression, while the values are the corresponding parameter values.

Method Details

__construct() method
public void __construct(string $expression, $params=array ( ))
$expression | string | the DB expression
$params |  |

Constructor.

__toString() method
public string __toString()
{return} string the DB expression

String magic method


CDbSchema

Package | system.db.schema
Inheritance | abstract class CDbSchema » CComponent
Subclasses | CMssqlSchema, CMysqlSchema, COciSchema, CPgsqlSchema, CSqliteSchema
Since | 1.0
Version | $Id: CDbSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbSchema is the base class for retrieving metadata information.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CDbSchema
compareTableNames() | Compares two table names. | CDbSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | CDbSchema
quoteTableName() | Quotes a table name for use in a query. | CDbSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CDbSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCommandBuilder() | Creates a command builder for the database. | CDbSchema
createTable() | Creates a table instance representing the metadata for the named table. | CDbSchema
findTableNames() | Returns all table names in the database. | CDbSchema

Property Details

commandBuilder property read-only
public CDbCommandBuilder getCommandBuilder()

the SQL command builder for this connection.

dbConnection property read-only
public CDbConnection getDbConnection()

database connection. The connection is active.

tableNames property read-only (available since v1.0.2)
public array getTableNames(string $schema='')

Returns all table names in the database.

tables property read-only (available since v1.0.2)
public array getTables(string $schema='')

Returns the metadata for all tables in the database.

Method Details

__construct() method
public void __construct(CDbConnection $conn)
$conn CDbConnection database connection.

Constructor.

checkIntegrity() method (available since v1.1)
public void checkIntegrity(boolean $check=true, string $schema='')
$check | boolean | whether to turn on or off the integrity check.
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema.

Enables or disables integrity check.

compareTableNames() method
public boolean compareTableNames(string $name1, string $name2)
$name1 | string | table name 1
$name2 | string | table name 2
{return} | boolean | whether the two table names refer to the same table.

Compares two table names. The table names can be either quoted or unquoted. This method will consider both cases.

createCommandBuilder() method
protected CDbCommandBuilder createCommandBuilder()
{return} CDbCommandBuilder command builder instance

Creates a command builder for the database. This method may be overridden by child classes to create a DBMS-specific command builder.

createTable() method
abstract protected CDbTableSchema createTable($name)
$name |  |
{return} | CDbTableSchema | driver dependent table metadata, null if the table does not exist.

Creates a table instance representing the metadata for the named table.

findTableNames() method (available since v1.0.2)
protected array findTableNames(string $schema='')
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema. If not empty, the returned table names will be prefixed with the schema name.
{return} | array | all table names in the database.

Returns all table names in the database. This method should be overridden by child classes in order to support this feature because the default implemenation simply throws an exception.

getCommandBuilder() method
public CDbCommandBuilder getCommandBuilder()
{return} CDbCommandBuilder the SQL command builder for this connection.

getDbConnection() method
public CDbConnection getDbConnection()
{return} CDbConnection database connection. The connection is active.

getTable() method
public CDbTableSchema getTable(string $name)
$name | string | table name
{return} | CDbTableSchema | table metadata. Null if the named table does not exist.

Obtains the metadata for the named table.

getTableNames() method (available since v1.0.2)
public array getTableNames(string $schema='')
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema. If not empty, the returned table names will be prefixed with the schema name.
{return} | array | all table names in the database.

Returns all table names in the database.

getTables() method (available since v1.0.2)
public array getTables(string $schema='')
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema.
{return} | array | the metadata for all tables in the database. Each array element is an instance of CDbTableSchema (or its child class). The array keys are table names.

Returns the metadata for all tables in the database.

quoteColumnName() method
public string quoteColumnName(string $name)
$name | string | column name
{return} | string | the properly quoted column name

Quotes a column name for use in a query.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

refresh() method
public void refresh()

Refreshes the schema. This method resets the loaded table metadata and command builder so that they can be recreated to reflect the change of schema.

resetSequence() method (available since v1.1)
public void resetSequence(CDbTableSchema $table, mixed $value=NULL)
$table | CDbTableSchema | the table schema whose primary key sequence will be reset
$value | mixed | the value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have a value 1.

Resets the sequence value of a table's primary key. The sequence will be reset such that the primary key of the next new row inserted will have the specified value or 1.


CDbTableSchema

Package | system.db.schema
Inheritance | class CDbTableSchema » CComponent
Subclasses | CMssqlTableSchema, CMysqlTableSchema, COciTableSchema, CPgsqlTableSchema
Since | 1.0
Version | $Id: CDbTableSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbTableSchema is the base class for representing the metadata of a database table.

It may be extended by different DBMS driver to provide DBMS-specific table metadata.

CDbTableSchema provides the following information about a table:
  • name
  • rawName
  • columns
  • primaryKey
  • foreignKeys
  • sequenceName

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
columnNames | array | list of column names | CDbTableSchema
columns | array | column metadata of this table. | CDbTableSchema
foreignKeys | array | foreign keys of this table. | CDbTableSchema
name | string | name of this table. | CDbTableSchema
primaryKey | string|array | primary key name of this table. | CDbTableSchema
rawName | string | raw name of this table. | CDbTableSchema
sequenceName | string | sequence name for the primary key. | CDbTableSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumn() | Gets the named column metadata. | CDbTableSchema
getColumnNames() |  | CDbTableSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

columnNames property read-only
public array getColumnNames()

list of column names

columns property
public array $columns;

column metadata of this table. Each array element is a CDbColumnSchema object, indexed by column names.

foreignKeys property
public array $foreignKeys;

foreign keys of this table. The array is indexed by column name. Each value is an array of foreign table name and foreign column name.

name property
public string $name;

name of this table.

primaryKey property
public string|array $primaryKey;

primary key name of this table. If composite key, an array of key names is returned.

rawName property
public string $rawName;

raw name of this table. This is the quoted version of table name with optional schema name. It can be directly used in SQLs.

sequenceName property
public string $sequenceName;

sequence name for the primary key. Null if no sequence.

Method Details

getColumn() method
public CDbColumnSchema getColumn(string $name)
$name | string | column name
{return} | CDbColumnSchema | metadata of the named column. Null if the named column does not exist.

Gets the named column metadata. This is a convenient method for retrieving a named column even if it does not exist.

getColumnNames() method
public array getColumnNames()
{return} array list of column names


CMssqlColumnSchema

Package | system.db.schema.mssql
Inheritance | class CMssqlColumnSchema » CDbColumnSchema » CComponent
Since | 1.0.4
Version | $Id: CMssqlColumnSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMssqlColumnSchema class describes the column meta data of a MSSQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() |  | CMssqlColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CMssqlColumnSchema
extractType() | Extracts the PHP type from DB type. | CMssqlColumnSchema

Method Details

extractDefault() method
protected void extractDefault($defaultValue)
$defaultValue

extractLimit() method
protected void extractLimit(string $dbType)
$dbType string the column's DB type

Extracts size, precision and scale information from column's DB type. We do nothing here, since sizes and precisions have been computed before.

extractType() method
protected void extractType(string $dbType)
$dbType string DB type

Extracts the PHP type from DB type.


CMssqlCommandBuilder

Package | system.db.schema.mssql
Inheritance | class CMssqlCommandBuilder » CDbCommandBuilder » CComponent
Since | 1.0.4
Version | $Id: CMssqlCommandBuilder.php 1907 2010-03-14 05:14:49Z qiang.xue $
CMssqlCommandBuilder provides basic methods to create query commands for tables for Mssql Servers.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | database connection. | CDbCommandBuilder
schema | CDbSchema | the schema for this command builder. | CDbCommandBuilder

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CDbCommandBuilder
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyCondition() | Alters the SQL to apply WHERE clause. | CDbCommandBuilder
applyGroup() | Alters the SQL to apply GROUP BY. | CDbCommandBuilder
applyHaving() | Alters the SQL to apply HAVING. | CDbCommandBuilder
applyJoin() | Alters the SQL to apply JOIN clause. | CDbCommandBuilder
applyLimit() | This is a port from Prado Framework. | CMssqlCommandBuilder
applyOrder() | Alters the SQL to apply ORDER BY. | CDbCommandBuilder
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindValues() | Binds parameter values for an SQL command. | CDbCommandBuilder
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createColumnCriteria() | Creates a query criteria with the specified column values. | CDbCommandBuilder
createCountCommand() | Creates a COUNT(*) command for a single table. | CMssqlCommandBuilder
createCriteria() | Creates a query criteria. | CDbCommandBuilder
createDeleteCommand() | Creates a DELETE command. | CMssqlCommandBuilder
createFindCommand() | Creates a SELECT command for a single table. | CMssqlCommandBuilder
createInCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createInsertCommand() | Creates an INSERT command. | CDbCommandBuilder
createPkCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createPkCriteria() | Creates a query criteria with the specified primary key. | CDbCommandBuilder
createSearchCondition() | Generates the expression for searching the specified keywords within a list of columns. | CDbCommandBuilder
createSqlCommand() | Creates a command based on a given SQL statement. | CDbCommandBuilder
createUpdateCommand() | Creates an UPDATE command. | CMssqlCommandBuilder
createUpdateCounterCommand() | Creates an UPDATE command that increments/decrements certain columns. | CMssqlCommandBuilder
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDbConnection() |  | CDbCommandBuilder
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLastInsertID() | Returns the last insertion ID for the specified table. | CMssqlCommandBuilder
getSchema() |  | CDbCommandBuilder
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
checkCriteria() | Checks if the criteria has an order by clause when using offset/limit. | CMssqlCommandBuilder
createCompositeInCondition() | Generates the expression for selecting rows with specified composite key values. | CDbCommandBuilder
ensureTable() | Checks if the parameter is a valid table schema. | CDbCommandBuilder
findOrdering() | Base on simplified syntax http://msdn2.microsoft.com/en-us/library/aa259187(SQL.80).aspx | CMssqlCommandBuilder
joinOrdering() |  | CMssqlCommandBuilder
reverseDirection() |  | CMssqlCommandBuilder
rewriteLimitOffsetSql() | Rewrite sql to apply $limit > and $offset > 0 for MSSQL database. | CMssqlCommandBuilder

Method Details

applyLimit() method
public string applyLimit(string $sql, integer $limit, integer $offset)
$sql | string | SQL query string.
$limit | integer | maximum number of rows, -1 to ignore limit.
$offset | integer | row offset, -1 to ignore offset.
{return} | string | SQL with limit and offset.

This is a port from Prado Framework.

Overrides parent implementation. Alters the sql to apply $limit and $offset. The idea for limit with offset is done by modifying the sql on the fly with numerous assumptions on the structure of the sql string. The modification is done with reference to the notes from http://troels.arvin.dk/db/rdbms/#select-limit-offset

SELECT * FROM ( SELECT TOP n * FROM ( SELECT TOP z columns -- (z=n+skip) FROM tablename ORDER BY key ASC ) AS FOO ORDER BY key DESC -- ('FOO' may be anything) ) AS BAR ORDER BY key ASC -- ('BAR' may be anything)

Regular expressions are used to alter the SQL query. The resulting SQL query may be malformed for complex queries. The following restrictions apply

  • In particular, commas should NOT be used as part of the ordering expression or identifier. Commas must only be used for separating the ordering clauses.
  • In the ORDER BY clause, the column name should NOT be be qualified with a table name or view name. Alias the column names or use column index.
  • No clauses should follow the ORDER BY clause, e.g. no COMPUTE or FOR clauses.

    • checkCriteria() method
    protected CDbCrireria checkCriteria(CMssqlTableSchema $table, CDbCriteria $criteria)
$table | CMssqlTableSchema | table schema
$criteria | CDbCriteria | criteria
{return} | CDbCrireria | the modified criteria

    Checks if the criteria has an order by clause when using offset/limit. Override parent implementation to check if an orderby clause if specified when querying with an offset If not, order it by pk.

    createCountCommand() method
    public CDbCommand createCountCommand(CDbTableSchema $table, CDbCriteria $criteria, string $alias='t')
$table | CDbTableSchema | the table metadata
$criteria | CDbCriteria | the query criteria
$alias | string | the alias name of the primary table. Defaults to 't'.
{return} | CDbCommand | query command.

    Creates a COUNT(*) command for a single table. Override parent implementation to remove the order clause of criteria if it exists

    createDeleteCommand() method
    public CDbCommand createDeleteCommand(CDbTableSchema $table, CDbCriteria $criteria)
$table | CDbTableSchema | the table metadata
$criteria | CDbCriteria | the query criteria
{return} | CDbCommand | delete command.

    Creates a DELETE command. Override parent implementation to check if an orderby clause if specified when querying with an offset

    createFindCommand() method
    public CDbCommand createFindCommand(CDbTableSchema $table, CDbCriteria $criteria, string $alias='t')
$table | CDbTableSchema | the table metadata
$criteria | CDbCriteria | the query criteria
$alias | string | the alias name of the primary table. Defaults to 't'.
{return} | CDbCommand | query command.

    Creates a SELECT command for a single table. Override parent implementation to check if an orderby clause if specified when querying with an offset

    createUpdateCommand() method
    public CDbCommand createUpdateCommand(CDbTableSchema $table, array $data, CDbCriteria $criteria)
$table | CDbTableSchema | the table metadata
$data | array | list of columns to be updated (name=>value)
$criteria | CDbCriteria | the query criteria
{return} | CDbCommand | update command.

    Creates an UPDATE command. Override parent implementation because mssql don't want to update an identity column

    createUpdateCounterCommand() method
    public CDbCommand createUpdateCounterCommand(CDbTableSchema $table, CDbCriteria $counters, array $criteria)
$table | CDbTableSchema | the table metadata
$counters | CDbCriteria | the query criteria
$criteria | array | counters to be updated (counter increments/decrements indexed by column names.)
{return} | CDbCommand | the created command

    Creates an UPDATE command that increments/decrements certain columns. Override parent implementation to check if an orderby clause if specified when querying with an offset

    findOrdering() method
    protected array findOrdering(string $sql)
$sql | string | $sql
{return} | array | ordering expression as key and ordering direction as value

    Base on simplified syntax http://msdn2.microsoft.com/en-us/library/aa259187(SQL.80).aspx

    getLastInsertID() method
    public mixed getLastInsertID(CDbTableSchema $table)
$table | CDbTableSchema | the table metadata
{return} | mixed | last insertion id. Null is returned if no sequence name.

    Returns the last insertion ID for the specified table. Override parent implemantation since PDO mssql driver does not provide this method

    joinOrdering() method
    protected string joinOrdering(array $orders)
$orders | array | ordering obtained from findOrdering()
{return} | string | concat the orderings

    reverseDirection() method
    protected array reverseDirection(array $orders)
$orders | array | original ordering
{return} | array | ordering with reversed direction.

    rewriteLimitOffsetSql() method
    protected sql rewriteLimitOffsetSql(string $sql, integer $limit, integer $offset)
$sql | string | sql query
$limit | integer | $limit > 0
$offset | integer | $offset > 0
{return} | sql | modified sql query applied with limit and offset.

    Rewrite sql to apply $limit > and $offset > 0 for MSSQL database. See http://troels.arvin.dk/db/rdbms/#select-limit-offset


CMssqlPdoAdapter

All Packages | Methods
Package | system.db.schema.mssql
Inheritance | class CMssqlPdoAdapter » PDO
Since | 1.0.4
Version | $Id: CMssqlPdoAdapter.php 1678 2010-01-07 21:02:00Z qiang.xue $
This is an extension of default PDO class for mssql driver only It provides some missing functionalities of pdo driver

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() |  | PDO
__sleep() |  | PDO
__wakeup() |  | PDO
beginTransaction() | Begin a transaction | CMssqlPdoAdapter
commit() | Commit a transaction | CMssqlPdoAdapter
errorCode() |  | PDO
errorInfo() |  | PDO
exec() |  | PDO
getAttribute() |  | PDO
getAvailableDrivers() |  | PDO
lastInsertId() | Get the last inserted id value | CMssqlPdoAdapter
prepare() |  | PDO
query() |  | PDO
quote() |  | PDO
rollBack() | Rollback a transaction | CMssqlPdoAdapter
setAttribute() |  | PDO

Method Details

beginTransaction() method
public boolean beginTransaction()
{return} boolean

Begin a transaction

Is is necessary to override pdo's method, as mssql pdo drivers does not support transaction

commit() method
public boolean commit()
{return} boolean

Commit a transaction

Is is necessary to override pdo's method, as mssql pdo drivers does not support transaction

lastInsertId() method
public int lastInsertId(string $sequence=NULL)
$sequence | string | sequence name. Defaults to null
{return} | int | last inserted id

Get the last inserted id value MSSQL doesn't support sequence, so, argument is ignored

rollBack() method
public boolean rollBack()
{return} boolean

Rollback a transaction

Is is necessary to override pdo's method, ac mssql pdo drivers does not support transaction


CMssqlSchema

Package | system.db.schema.mssql
Inheritance | class CMssqlSchema » CDbSchema » CComponent
Since | 1.0.4
Version | $Id: CMssqlSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMssqlSchema is the class for retrieving metadata information from a MS SQL Server database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CDbSchema
compareTableNames() | Compares two table names. | CMssqlSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | CMssqlSchema
quoteTableName() | Quotes a table name for use in a query. | CMssqlSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CDbSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createColumn() | Creates a table column. | CMssqlSchema
createCommandBuilder() | Creates a command builder for the database. | CMssqlSchema
createTable() | Creates a table instance representing the metadata for the named table. | CMssqlSchema
findColumns() | Collects the table column metadata. | CMssqlSchema
findForeignKeys() | Gets foreign relationship constraint keys and table name | CMssqlSchema
findPrimaryKey() | Gets the primary key column(s) details for the given table. | CMssqlSchema
findTableNames() | Returns all table names in the database. | CMssqlSchema
resolveTableNames() | Generates various kinds of table names. | CMssqlSchema

Method Details

compareTableNames() method
public boolean compareTableNames(string $name1, string $name2)
$name1 | string | table name 1
$name2 | string | table name 2
{return} | boolean | whether the two table names refer to the same table.

Compares two table names. The table names can be either quoted or unquoted. This method will consider both cases.

createColumn() method
protected CDbColumnSchema createColumn(array $column)
$column | array | column metadata
{return} | CDbColumnSchema | normalized column metadata

Creates a table column.

createCommandBuilder() method
protected CDbCommandBuilder createCommandBuilder()
{return} CDbCommandBuilder command builder instance

Creates a command builder for the database. This method overrides parent implementation in order to create a MSSQL specific command builder

createTable() method
protected CMssqlTableSchema createTable($name)
$name |  |
{return} | CMssqlTableSchema | driver dependent table metadata. Null if the table does not exist.

Creates a table instance representing the metadata for the named table.

findColumns() method
protected boolean findColumns(CMssqlTableSchema $table)
$table | CMssqlTableSchema | the table metadata
{return} | boolean | whether the table exists in the database

Collects the table column metadata.

findForeignKeys() method
protected array findForeignKeys(CMssqlTableSchema $table)
$table | CMssqlTableSchema | table
{return} | array | foreign relationship table name and keys.

Gets foreign relationship constraint keys and table name

findPrimaryKey() method
protected mixed findPrimaryKey(CMssqlTableSchema $table)
$table | CMssqlTableSchema | table
{return} | mixed | primary keys (null if no pk, string if only 1 column pk, or array if composite pk)

Gets the primary key column(s) details for the given table.

findTableNames() method (available since v1.0.4)
protected array findTableNames($schema='')
$schema |  |
{return} | array | all table names in the database.

Returns all table names in the database.

quoteColumnName() method
public string quoteColumnName(string $name)
$name | string | column name
{return} | string | the properly quoted column name

Quotes a column name for use in a query.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

resolveTableNames() method
protected void resolveTableNames(CMssqlTableSchema $table, string $name)
$table | CMssqlTableSchema | the table instance
$name | string | the unquoted table name

Generates various kinds of table names.


CMssqlTableSchema

Package | system.db.schema.mssql
Inheritance | class CMssqlTableSchema » CDbTableSchema » CComponent
Since | 1.0.4
Version | $Id: CMssqlTableSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMssqlTableSchema represents the metadata for a MSSQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
catalogName | string | name of the catalog (database) that this table belongs to. | CMssqlTableSchema
columnNames | array | list of column names | CDbTableSchema
columns | array | column metadata of this table. | CDbTableSchema
foreignKeys | array | foreign keys of this table. | CDbTableSchema
name | string | name of this table. | CDbTableSchema
primaryKey | string|array | primary key name of this table. | CDbTableSchema
rawName | string | raw name of this table. | CDbTableSchema
schemaName | string | name of the schema that this table belongs to. | CMssqlTableSchema
sequenceName | string | sequence name for the primary key. | CDbTableSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumn() | Gets the named column metadata. | CDbTableSchema
getColumnNames() |  | CDbTableSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

catalogName property
public string $catalogName;

name of the catalog (database) that this table belongs to. Defaults to null, meaning no schema (or the current database).

schemaName property
public string $schemaName;

name of the schema that this table belongs to. Defaults to null, meaning no schema (or the current database owner).


CMysqlColumnSchema

Package | system.db.schema.mysql
Inheritance | class CMysqlColumnSchema » CDbColumnSchema » CComponent
Since | 1.0
Version | $Id: CMysqlColumnSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMysqlColumnSchema class describes the column meta data of a MySQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() |  | CMysqlColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CMysqlColumnSchema
extractType() | Extracts the PHP type from DB type. | CMysqlColumnSchema

Method Details

extractDefault() method
protected void extractDefault($defaultValue)
$defaultValue

extractLimit() method
protected void extractLimit(string $dbType)
$dbType string the column's DB type

Extracts size, precision and scale information from column's DB type.

extractType() method
protected void extractType(string $dbType)
$dbType string DB type

Extracts the PHP type from DB type.


CMysqlSchema

Package | system.db.schema.mysql
Inheritance | class CMysqlSchema » CDbSchema » CComponent
Since | 1.0
Version | $Id: CMysqlSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMysqlSchema is the class for retrieving metadata information from a MySQL database (version 4.1.x and 5.x).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
serverVersion | float | server version. | CMysqlSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CMysqlSchema
compareTableNames() | Compares two table names. | CMysqlSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | CMysqlSchema
quoteTableName() | Quotes a table name for use in a query. | CMysqlSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CMysqlSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createColumn() | Creates a table column. | CMysqlSchema
createCommandBuilder() | Creates a command builder for the database. | CDbSchema
createTable() | Creates a table instance representing the metadata for the named table. | CMysqlSchema
findColumns() | Collects the table column metadata. | CMysqlSchema
findConstraints() | Collects the foreign key column details for the given table. | CMysqlSchema
findTableNames() | Returns all table names in the database. | CMysqlSchema
getServerVersion() |  | CMysqlSchema
resolveTableNames() | Generates various kinds of table names. | CMysqlSchema

Property Details

serverVersion property read-only
protected float getServerVersion()

server version.

Method Details

checkIntegrity() method (available since v1.1)
public void checkIntegrity(boolean $check=true, string $schema='')
$check | boolean | whether to turn on or off the integrity check.
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema.

Enables or disables integrity check.

compareTableNames() method
public boolean compareTableNames(string $name1, string $name2)
$name1 | string | table name 1
$name2 | string | table name 2
{return} | boolean | whether the two table names refer to the same table.

Compares two table names. The table names can be either quoted or unquoted. This method will consider both cases.

createColumn() method
protected CDbColumnSchema createColumn(array $column)
$column | array | column metadata
{return} | CDbColumnSchema | normalized column metadata

Creates a table column.

createTable() method
protected CMysqlTableSchema createTable($name)
$name |  |
{return} | CMysqlTableSchema | driver dependent table metadata. Null if the table does not exist.

Creates a table instance representing the metadata for the named table.

findColumns() method
protected boolean findColumns(CMysqlTableSchema $table)
$table | CMysqlTableSchema | the table metadata
{return} | boolean | whether the table exists in the database

Collects the table column metadata.

findConstraints() method
protected void findConstraints(CMysqlTableSchema $table)
$table CMysqlTableSchema the table metadata

Collects the foreign key column details for the given table.

findTableNames() method (available since v1.0.2)
protected array findTableNames($schema='')
$schema |  |
{return} | array | all table names in the database.

Returns all table names in the database.

getServerVersion() method
protected float getServerVersion()
{return} float server version.

quoteColumnName() method
public string quoteColumnName(string $name)
$name | string | column name
{return} | string | the properly quoted column name

Quotes a column name for use in a query.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

resetSequence() method (available since v1.1)
public void resetSequence(CDbTableSchema $table, mixed $value=NULL)
$table | CDbTableSchema | the table schema whose primary key sequence will be reset
$value | mixed | the value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have a value 1.

Resets the sequence value of a table's primary key. The sequence will be reset such that the primary key of the next new row inserted will have the specified value or 1.

resolveTableNames() method
protected void resolveTableNames(CMysqlTableSchema $table, string $name)
$table | CMysqlTableSchema | the table instance
$name | string | the unquoted table name

Generates various kinds of table names.


CMysqlTableSchema

Package | system.db.schema.mysql
Inheritance | class CMysqlTableSchema » CDbTableSchema » CComponent
Since | 1.0
Version | $Id: CMysqlTableSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMysqlTableSchema represents the metadata for a MySQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
columnNames | array | list of column names | CDbTableSchema
columns | array | column metadata of this table. | CDbTableSchema
foreignKeys | array | foreign keys of this table. | CDbTableSchema
name | string | name of this table. | CDbTableSchema
primaryKey | string|array | primary key name of this table. | CDbTableSchema
rawName | string | raw name of this table. | CDbTableSchema
schemaName | string | name of the schema (database) that this table belongs to. | CMysqlTableSchema
sequenceName | string | sequence name for the primary key. | CDbTableSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumn() | Gets the named column metadata. | CDbTableSchema
getColumnNames() |  | CDbTableSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

schemaName property
public string $schemaName;

name of the schema (database) that this table belongs to. Defaults to null, meaning no schema (or the current database).


COciColumnSchema

Package | system.db.schema.oci
Inheritance | class COciColumnSchema » CDbColumnSchema » CComponent
Since | 1.0.5
Version | $Id: COciColumnSchema.php 1826 2010-02-20 00:40:28Z qiang.xue $
COciColumnSchema class describes the column meta data of a Oracle table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() |  | COciColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CDbColumnSchema
extractOraType() | Extracts the PHP type from DB type. | COciColumnSchema
extractType() |  | COciColumnSchema

Method Details

extractDefault() method
protected void extractDefault($defaultValue)
$defaultValue

extractOraType() method
protected void extractOraType(string $dbType)
$dbType string DB type

Extracts the PHP type from DB type.

extractType() method
protected void extractType($dbType)
$dbType


COciCommandBuilder

Package | system.db.schema.oci
Inheritance | class COciCommandBuilder » CDbCommandBuilder » CComponent
Since | 1.0.5
Version | $Id: COciCommandBuilder.php 1867 2010-03-09 18:22:16Z qiang.xue $
COciCommandBuilder provides basic methods to create query commands for tables.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | database connection. | CDbCommandBuilder
returnID | integer | the last insertion ID | COciCommandBuilder
schema | CDbSchema | the schema for this command builder. | CDbCommandBuilder

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CDbCommandBuilder
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyCondition() | Alters the SQL to apply WHERE clause. | CDbCommandBuilder
applyGroup() | Alters the SQL to apply GROUP BY. | CDbCommandBuilder
applyHaving() | Alters the SQL to apply HAVING. | CDbCommandBuilder
applyJoin() | Alters the SQL to apply JOIN clause. | CDbCommandBuilder
applyLimit() | Alters the SQL to apply LIMIT and OFFSET. | COciCommandBuilder
applyOrder() | Alters the SQL to apply ORDER BY. | CDbCommandBuilder
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindValues() | Binds parameter values for an SQL command. | CDbCommandBuilder
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createColumnCriteria() | Creates a query criteria with the specified column values. | CDbCommandBuilder
createCountCommand() | Creates a COUNT(*) command for a single table. | CDbCommandBuilder
createCriteria() | Creates a query criteria. | CDbCommandBuilder
createDeleteCommand() | Creates a DELETE command. | CDbCommandBuilder
createFindCommand() | Creates a SELECT command for a single table. | CDbCommandBuilder
createInCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createInsertCommand() | Creates an INSERT command. | COciCommandBuilder
createPkCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createPkCriteria() | Creates a query criteria with the specified primary key. | CDbCommandBuilder
createSearchCondition() | Generates the expression for searching the specified keywords within a list of columns. | CDbCommandBuilder
createSqlCommand() | Creates a command based on a given SQL statement. | CDbCommandBuilder
createUpdateCommand() | Creates an UPDATE command. | CDbCommandBuilder
createUpdateCounterCommand() | Creates an UPDATE command that increments/decrements certain columns. | CDbCommandBuilder
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDbConnection() |  | CDbCommandBuilder
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLastInsertID() | Returns the last insertion ID for the specified table. | COciCommandBuilder
getSchema() |  | CDbCommandBuilder
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCompositeInCondition() | Generates the expression for selecting rows with specified composite key values. | CDbCommandBuilder
ensureTable() | Checks if the parameter is a valid table schema. | CDbCommandBuilder

Property Details

returnID property
public integer $returnID;

the last insertion ID

Method Details

applyLimit() method
public string applyLimit(string $sql, integer $limit, integer $offset)
$sql | string | SQL query string without LIMIT and OFFSET.
$limit | integer | maximum number of rows, -1 to ignore limit.
$offset | integer | row offset, -1 to ignore offset.
{return} | string | SQL with LIMIT and OFFSET

Alters the SQL to apply LIMIT and OFFSET. Default implementation is applicable for PostgreSQL, MySQL and SQLite.

createInsertCommand() method
public CDbCommand createInsertCommand(mixed $table, array $data)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
$data | array | data to be inserted (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
{return} | CDbCommand | insert command

Creates an INSERT command.

getLastInsertID() method
public mixed getLastInsertID(mixed $table)
$table | mixed | the table schema (CDbTableSchema) or the table name (string).
{return} | mixed | last insertion id. Null is returned if no sequence name.

Returns the last insertion ID for the specified table.


COciSchema

Package | system.db.schema.oci
Inheritance | class COciSchema » CDbSchema » CComponent
Since | 1.0.5
Version | $Id: COciSchema.php 1864 2010-03-08 22:32:22Z qiang.xue $
COciSchema is the class for retrieving metadata information from an Oracle database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
defaultSchema | string | default schema. | COciSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CDbSchema
compareTableNames() | Compares two table names. | CDbSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getDefaultSchema() |  | COciSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | COciSchema
quoteTableName() | Quotes a table name for use in a query. | COciSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CDbSchema
setDefaultSchema() |  | COciSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createColumn() | Creates a table column. | COciSchema
createCommandBuilder() | Creates a command builder for the database. | COciSchema
createTable() | Creates a table instance representing the metadata for the named table. | COciSchema
findColumns() | Collects the table column metadata. | COciSchema
findConstraints() | Collects the primary and foreign key column details for the given table. | COciSchema
findTableNames() | Returns all table names in the database. | COciSchema
getSchemaTableName() |  | COciSchema
resolveTableNames() | Generates various kinds of table names. | COciSchema

Property Details

defaultSchema property
public string getDefaultSchema()
public void setDefaultSchema(string $schema)

default schema.

Method Details

createColumn() method
protected CDbColumnSchema createColumn(array $column)
$column | array | column metadata
{return} | CDbColumnSchema | normalized column metadata

Creates a table column.

createCommandBuilder() method
protected CDbCommandBuilder createCommandBuilder()
{return} CDbCommandBuilder command builder instance

Creates a command builder for the database. This method may be overridden by child classes to create a DBMS-specific command builder.

createTable() method
protected CDbTableSchema createTable($name)
$name |  |
{return} | CDbTableSchema | driver dependent table metadata.

Creates a table instance representing the metadata for the named table.

findColumns() method
protected boolean findColumns(COciTableSchema $table)
$table | COciTableSchema | the table metadata
{return} | boolean | whether the table exists in the database

Collects the table column metadata.

findConstraints() method
protected void findConstraints(COciTableSchema $table)
$table COciTableSchema the table metadata

Collects the primary and foreign key column details for the given table.

findTableNames() method
protected array findTableNames($schema='')
$schema |  |
{return} | array | all table names in the database.

Returns all table names in the database.

getDefaultSchema() method
public string getDefaultSchema()
{return} string default schema.

getSchemaTableName() method
protected array getSchemaTableName(string $table)
$table | string | table name with optional schema name prefix, uses default schema name prefix is not provided.
{return} | array | tuple as ($schemaName,$tableName)

quoteColumnName() method
public string quoteColumnName(string $name)
$name | string | column name
{return} | string | the properly quoted column name

Quotes a column name for use in a query.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

resolveTableNames() method
protected void resolveTableNames(COciTableSchema $table, string $name)
$table | COciTableSchema | the table instance
$name | string | the unquoted table name

Generates various kinds of table names.

setDefaultSchema() method
public void setDefaultSchema(string $schema)
$schema string default schema.


COciTableSchema

Package | system.db.schema.oci
Inheritance | class COciTableSchema » CDbTableSchema » CComponent
Since | 1.0.5
Version | $Id: COciTableSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
COciTableSchema represents the metadata for a Oracle table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
columnNames | array | list of column names | CDbTableSchema
columns | array | column metadata of this table. | CDbTableSchema
foreignKeys | array | foreign keys of this table. | CDbTableSchema
name | string | name of this table. | CDbTableSchema
primaryKey | string|array | primary key name of this table. | CDbTableSchema
rawName | string | raw name of this table. | CDbTableSchema
schemaName | string | name of the schema (database) that this table belongs to. | COciTableSchema
sequenceName | string | sequence name for the primary key. | CDbTableSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumn() | Gets the named column metadata. | CDbTableSchema
getColumnNames() |  | CDbTableSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

schemaName property
public string $schemaName;

name of the schema (database) that this table belongs to. Defaults to null, meaning no schema (or the current database).


CPgsqlColumnSchema

Package | system.db.schema.pgsql
Inheritance | class CPgsqlColumnSchema » CDbColumnSchema » CComponent
Since | 1.0
Version | $Id: CPgsqlColumnSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPgsqlColumnSchema class describes the column meta data of a PostgreSQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() | Extracts the default value for the column. | CPgsqlColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CDbColumnSchema
extractType() | Extracts the PHP type from DB type. | CPgsqlColumnSchema

Method Details

extractDefault() method
protected void extractDefault(mixed $defaultValue)
$defaultValue mixed the default value obtained from metadata

Extracts the default value for the column. The value is typecasted to correct PHP type.

extractType() method
protected void extractType(string $dbType)
$dbType string DB type

Extracts the PHP type from DB type.


CPgsqlSchema

Package | system.db.schema.pgsql
Inheritance | class CPgsqlSchema » CDbSchema » CComponent
Since | 1.0
Version | $Id: CPgsqlSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPgsqlSchema is the class for retrieving metadata information from a PostgreSQL database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CPgsqlSchema
compareTableNames() | Compares two table names. | CDbSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | CDbSchema
quoteTableName() | Quotes a table name for use in a query. | CPgsqlSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CPgsqlSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createColumn() | Creates a table column. | CPgsqlSchema
createCommandBuilder() | Creates a command builder for the database. | CDbSchema
createTable() | Creates a table instance representing the metadata for the named table. | CPgsqlSchema
findColumns() | Collects the table column metadata. | CPgsqlSchema
findConstraints() | Collects the primary and foreign key column details for the given table. | CPgsqlSchema
findForeignKey() | Collects foreign key information. | CPgsqlSchema
findPrimaryKey() | Collects primary key information. | CPgsqlSchema
findTableNames() | Returns all table names in the database. | CPgsqlSchema
resolveTableNames() | Generates various kinds of table names. | CPgsqlSchema

Method Details

checkIntegrity() method (available since v1.1)
public void checkIntegrity(boolean $check=true, string $schema='')
$check | boolean | whether to turn on or off the integrity check.
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema.

Enables or disables integrity check.

createColumn() method
protected CDbColumnSchema createColumn(array $column)
$column | array | column metadata
{return} | CDbColumnSchema | normalized column metadata

Creates a table column.

createTable() method
protected CDbTableSchema createTable($name)
$name |  |
{return} | CDbTableSchema | driver dependent table metadata.

Creates a table instance representing the metadata for the named table.

findColumns() method
protected boolean findColumns(CPgsqlTableSchema $table)
$table | CPgsqlTableSchema | the table metadata
{return} | boolean | whether the table exists in the database

Collects the table column metadata.

findConstraints() method
protected void findConstraints(CPgsqlTableSchema $table)
$table CPgsqlTableSchema the table metadata

Collects the primary and foreign key column details for the given table.

findForeignKey() method
protected void findForeignKey(CPgsqlTableSchema $table, string $src)
$table | CPgsqlTableSchema | the table metadata
$src | string | pgsql foreign key definition

Collects foreign key information.

findPrimaryKey() method
protected void findPrimaryKey(CPgsqlTableSchema $table, string $indices)
$table | CPgsqlTableSchema | the table metadata
$indices | string | pgsql primary key index list

Collects primary key information.

findTableNames() method (available since v1.0.2)
protected array findTableNames($schema='')
$schema |  |
{return} | array | all table names in the database.

Returns all table names in the database.

quoteTableName() method
public string quoteTableName(string $name)
$name | string | table name
{return} | string | the properly quoted table name

Quotes a table name for use in a query.

resetSequence() method (available since v1.1)
public void resetSequence(CDbTableSchema $table, mixed $value=NULL)
$table | CDbTableSchema | the table schema whose primary key sequence will be reset
$value | mixed | the value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have a value 1.

Resets the sequence value of a table's primary key. The sequence will be reset such that the primary key of the next new row inserted will have the specified value or 1.

resolveTableNames() method
protected void resolveTableNames(CPgsqlTableSchema $table, string $name)
$table | CPgsqlTableSchema | the table instance
$name | string | the unquoted table name

Generates various kinds of table names.


CPgsqlTableSchema

Package | system.db.schema.pgsql
Inheritance | class CPgsqlTableSchema » CDbTableSchema » CComponent
Since | 1.0
Version | $Id: CPgsqlTableSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPgsqlTable represents the metadata for a PostgreSQL table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
columnNames | array | list of column names | CDbTableSchema
columns | array | column metadata of this table. | CDbTableSchema
foreignKeys | array | foreign keys of this table. | CDbTableSchema
name | string | name of this table. | CDbTableSchema
primaryKey | string|array | primary key name of this table. | CDbTableSchema
rawName | string | raw name of this table. | CDbTableSchema
schemaName | string | name of the schema that this table belongs to. | CPgsqlTableSchema
sequenceName | string | sequence name for the primary key. | CDbTableSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getColumn() | Gets the named column metadata. | CDbTableSchema
getColumnNames() |  | CDbTableSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

schemaName property
public string $schemaName;

name of the schema that this table belongs to.


CSqliteColumnSchema

Package | system.db.schema.sqlite
Inheritance | class CSqliteColumnSchema » CDbColumnSchema » CComponent
Since | 1.0
Version | $Id: CSqliteColumnSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSqliteColumnSchema class describes the column meta data of a SQLite table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowNull | boolean | whether this column can be null. | CDbColumnSchema
dbType | string | the DB type of this column. | CDbColumnSchema
defaultValue | mixed | default value of this column | CDbColumnSchema
isForeignKey | boolean | whether this column is a foreign key | CDbColumnSchema
isPrimaryKey | boolean | whether this column is a primary key | CDbColumnSchema
name | string | name of this column (without quotes). | CDbColumnSchema
precision | integer | precision of the column data, if it is numeric. | CDbColumnSchema
rawName | string | raw name of this column. | CDbColumnSchema
scale | integer | scale of the column data, if it is numeric. | CDbColumnSchema
size | integer | size of the column. | CDbColumnSchema
type | string | the PHP type of this column. | CDbColumnSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column with its DB type and default value. | CDbColumnSchema
raiseEvent() | Raises an event. | CComponent
typecast() | Converts the input value to the type that this column is of. | CDbColumnSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
extractDefault() | Extracts the default value for the column. | CSqliteColumnSchema
extractLimit() | Extracts size, precision and scale information from column's DB type. | CDbColumnSchema
extractType() | Extracts the PHP type from DB type. | CDbColumnSchema

Method Details

extractDefault() method
protected void extractDefault(mixed $defaultValue)
$defaultValue mixed the default value obtained from metadata

Extracts the default value for the column. The value is typecasted to correct PHP type.


CSqliteCommandBuilder

Package | system.db.schema.sqlite
Inheritance | class CSqliteCommandBuilder » CDbCommandBuilder » CComponent
Since | 1.0
Version | $Id: CSqliteCommandBuilder.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSqliteCommandBuilder provides basic methods to create query commands for SQLite tables.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | database connection. | CDbCommandBuilder
schema | CDbSchema | the schema for this command builder. | CDbCommandBuilder

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CDbCommandBuilder
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyCondition() | Alters the SQL to apply WHERE clause. | CDbCommandBuilder
applyGroup() | Alters the SQL to apply GROUP BY. | CDbCommandBuilder
applyHaving() | Alters the SQL to apply HAVING. | CDbCommandBuilder
applyJoin() | Alters the SQL to apply JOIN clause. | CDbCommandBuilder
applyLimit() | Alters the SQL to apply LIMIT and OFFSET. | CDbCommandBuilder
applyOrder() | Alters the SQL to apply ORDER BY. | CDbCommandBuilder
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
bindValues() | Binds parameter values for an SQL command. | CDbCommandBuilder
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createColumnCriteria() | Creates a query criteria with the specified column values. | CDbCommandBuilder
createCountCommand() | Creates a COUNT(*) command for a single table. | CDbCommandBuilder
createCriteria() | Creates a query criteria. | CDbCommandBuilder
createDeleteCommand() | Creates a DELETE command. | CDbCommandBuilder
createFindCommand() | Creates a SELECT command for a single table. | CDbCommandBuilder
createInCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createInsertCommand() | Creates an INSERT command. | CDbCommandBuilder
createPkCondition() | Generates the expression for selecting rows of specified primary key values. | CDbCommandBuilder
createPkCriteria() | Creates a query criteria with the specified primary key. | CDbCommandBuilder
createSearchCondition() | Generates the expression for searching the specified keywords within a list of columns. | CDbCommandBuilder
createSqlCommand() | Creates a command based on a given SQL statement. | CDbCommandBuilder
createUpdateCommand() | Creates an UPDATE command. | CDbCommandBuilder
createUpdateCounterCommand() | Creates an UPDATE command that increments/decrements certain columns. | CDbCommandBuilder
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDbConnection() |  | CDbCommandBuilder
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLastInsertID() | Returns the last insertion ID for the specified table. | CDbCommandBuilder
getSchema() |  | CDbCommandBuilder
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCompositeInCondition() | Generates the expression for selecting rows with specified composite key values. | CSqliteCommandBuilder
ensureTable() | Checks if the parameter is a valid table schema. | CDbCommandBuilder

Method Details

createCompositeInCondition() method (available since v1.0.4)
protected string createCompositeInCondition(CDbTableSchema $table, array $values, string $prefix)
$table | CDbTableSchema | the table schema
$values | array | list of primary key values to be selected within
$prefix | string | column prefix (ended with dot)
{return} | string | the expression for selection

Generates the expression for selecting rows with specified composite key values. This method is overridden because SQLite does not support the default IN expression with composite columns.


CSqliteSchema

Package | system.db.schema.sqlite
Inheritance | class CSqliteSchema » CDbSchema » CComponent
Since | 1.0
Version | $Id: CSqliteSchema.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSqliteSchema is the class for retrieving metadata information from a SQLite (2/3) database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
commandBuilder | CDbCommandBuilder | the SQL command builder for this connection. | CDbSchema
dbConnection | CDbConnection | database connection. | CDbSchema
tableNames | array | Returns all table names in the database. | CDbSchema
tables | array | Returns the metadata for all tables in the database. | CDbSchema

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDbSchema
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables integrity check. | CSqliteSchema
compareTableNames() | Compares two table names. | CDbSchema
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCommandBuilder() |  | CDbSchema
getDbConnection() |  | CDbSchema
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getTable() | Obtains the metadata for the named table. | CDbSchema
getTableNames() | Returns all table names in the database. | CDbSchema
getTables() | Returns the metadata for all tables in the database. | CDbSchema
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
quoteColumnName() | Quotes a column name for use in a query. | CDbSchema
quoteTableName() | Quotes a table name for use in a query. | CDbSchema
raiseEvent() | Raises an event. | CComponent
refresh() | Refreshes the schema. | CDbSchema
resetSequence() | Resets the sequence value of a table's primary key. | CSqliteSchema

Protected Methods

Hide inherited methods

Method | Description | Defined By
createColumn() | Creates a table column. | CSqliteSchema
createCommandBuilder() | Creates a command builder for the database. | CSqliteSchema
createTable() | Creates a table instance representing the metadata for the named table. | CSqliteSchema
findColumns() | Collects the table column metadata. | CSqliteSchema
findConstraints() | Collects the foreign key column details for the given table. | CSqliteSchema
findTableNames() | Returns all table names in the database. | CSqliteSchema

Method Details

checkIntegrity() method (available since v1.1)
public void checkIntegrity(boolean $check=true, string $schema='')
$check | boolean | whether to turn on or off the integrity check.
$schema | string | the schema of the tables. Defaults to empty string, meaning the current or default schema.

Enables or disables integrity check.

createColumn() method
protected CDbColumnSchema createColumn(array $column)
$column | array | column metadata
{return} | CDbColumnSchema | normalized column metadata

Creates a table column.

createCommandBuilder() method
protected CSqliteCommandBuilder createCommandBuilder()
{return} CSqliteCommandBuilder command builder instance

Creates a command builder for the database.

createTable() method
protected CDbTableSchema createTable($name)
$name |  |
{return} | CDbTableSchema | driver dependent table metadata. Null if the table does not exist.

Creates a table instance representing the metadata for the named table.

findColumns() method
protected boolean findColumns(CDbTableSchema $table)
$table | CDbTableSchema | the table metadata
{return} | boolean | whether the table exists in the database

Collects the table column metadata.

findConstraints() method
protected void findConstraints(CDbTableSchema $table)
$table CDbTableSchema the table metadata

Collects the foreign key column details for the given table.

findTableNames() method (available since v1.0.2)
protected array findTableNames(string $schema='')
$schema | string | the schema of the tables. This is not used for sqlite database.
{return} | array | all table names in the database.

Returns all table names in the database.

resetSequence() method (available since v1.1)
public void resetSequence(CDbTableSchema $table, mixed $value=NULL)
$table | CDbTableSchema | the table schema whose primary key sequence will be reset
$value | mixed | the value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have a value 1.

Resets the sequence value of a table's primary key. The sequence will be reset such that the primary key of the next new row inserted will have the specified value or 1.


CChoiceFormat

All Packages | Methods
Package | system.i18n
Inheritance | class CChoiceFormat
Since | 1.0.2
Version | $Id: CChoiceFormat.php 1743 2010-01-22 18:53:15Z qiang.xue $
CChoiceFormat is a helper that chooses an appropriate message based on the specified number value. The candidate messages are given as a string in the following format:
'expr1#message1|expr2#message2|expr3#message3'
where each expression should be a valid PHP expression with 'n' as the only variable. For example, 'n==1' and 'n%10==2 && n>10' are both valid expressions. The variable 'n' will take the given number value, and if an expression evaluates true, the corresponding message will be returned.

For example, given the candidate messages 'n==1#one|n==2#two|n>2#others' and the number value 2, the resulting message will be 'two'.

For expressions like 'n==1', we can also use a shortcut '1'. So the above example candidate messages can be simplified as '1#one|2#two|n>2#others'.

In case the given number doesn't select any message, the last candidate message will be returned.

Public Methods

Hide inherited methods

Method | Description | Defined By
format() | Formats a message according to the specified number value. | CChoiceFormat

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluate() | Evaluates a PHP expression with the given number value. | CChoiceFormat

Method Details

evaluate() method
protected static boolean evaluate(string $expression, mixed $n)
$expression | string | the PHP expression
$n | mixed | the number value
{return} | boolean | the expression result

Evaluates a PHP expression with the given number value.

format() method
public static string format(string $messages, mixed $number)
$messages | string | the candidate messages in the format of 'expr1#message1|expr2#message2|expr3#message3'. See CChoiceFormat for more details.
$number | mixed | the number value
{return} | string | the selected message

Formats a message according to the specified number value.


CDateFormatter

All Packages | Methods
Package | system.i18n
Inheritance | class CDateFormatter » CComponent
Since | 1.0
Version | $Id: CDateFormatter.php 1771 2010-02-01 03:39:06Z qiang.xue $
CDateFormatter provides date/time localization functionalities.

CDateFormatter allows you to format dates and times in a locale-sensitive manner. Patterns are interpretted in the locale that the CDateFormatter instance is associated with. For example, month names and weekday names may vary under different locales, which yields different formatting results. The patterns that CDateFormatter recognizes are as defined in CLDR.

CDateFormatter supports predefined patterns as well as customized ones:
  • The method formatDateTime() formats date or time or both using predefined patterns which include 'full', 'long', 'medium' (default) and 'short'.
  • The method format() formats datetime using the specified pattern. See http://www.unicode.org/reports/tr35/#Date_Format_Patterns for details about the recognized pattern characters.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CDateFormatter
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
format() | Formats a date according to a customized pattern. | CDateFormatter
formatDateTime() | Formats a date according to a predefined pattern. | CDateFormatter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatDay() | Get the day of the month. | CDateFormatter
formatDayInMonth() | Get day of week in the month, e.g. 2nd Wed in July. | CDateFormatter
formatDayInWeek() | Get the day of the week. | CDateFormatter
formatDayInYear() | Get the day in the year, e.g. [1-366] | CDateFormatter
formatEra() | Get the era. i.e. in gregorian, year > 0 is AD, else BC. | CDateFormatter
formatHour12() | Get the hours in 12 hour format, i.e., [1-12] | CDateFormatter
formatHour24() | Get the hours in 24 hour format, i.e. [0-23]. | CDateFormatter
formatHourInDay() | Get the hours [1-24]. | CDateFormatter
formatHourInPeriod() | Get the hours in AM/PM format, e.g [0-11] | CDateFormatter
formatMinutes() | Get the minutes. | CDateFormatter
formatMonth() | Get the month. | CDateFormatter
formatPeriod() | Get the AM/PM designator, 12 noon is PM, 12 midnight is AM. | CDateFormatter
formatSeconds() | Get the seconds. | CDateFormatter
formatTimeZone() | Get the timezone of the server machine. | CDateFormatter
formatWeekInMonth() | Get week in the month. | CDateFormatter
formatWeekInYear() | Get the week in the year. | CDateFormatter
formatYear() | Get the year. | CDateFormatter
parseFormat() | Parses the datetime format pattern. | CDateFormatter

Method Details

__construct() method
public void __construct(mixed $locale)
$locale mixed locale ID (string) or CLocale instance

Constructor.

format() method
public string format(string $pattern, mixed $time)
$pattern | string | the pattern (See http://www.unicode.org/reports/tr35/#Date_Format_Patterns)
$time | mixed | UNIX timestamp or a string in strtotime format
{return} | string | formatted date time.

Formats a date according to a customized pattern.

formatDateTime() method
public string formatDateTime(mixed $timestamp, string $dateWidth='medium', string $timeWidth='medium')
$timestamp | mixed | UNIX timestamp or a string in strtotime format
$dateWidth | string | width of the date pattern. It can be 'full', 'long', 'medium' and 'short'. If null, it means the date portion will NOT appear in the formatting result
$timeWidth | string | width of the time pattern. It can be 'full', 'long', 'medium' and 'short'. If null, it means the time portion will NOT appear in the formatting result
{return} | string | formatted date time.

Formats a date according to a predefined pattern. The predefined pattern is determined based on the date pattern width and time pattern width.

formatDay() method
protected string formatDay(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | day of the month

Get the day of the month. "d" for non-padding, "dd" will always return 2 digits day numbers, e.g. 05.

formatDayInMonth() method
protected int formatDayInMonth(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | int | day in month

Get day of week in the month, e.g. 2nd Wed in July.

formatDayInWeek() method
protected string formatDayInWeek(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | day of the week.

Get the day of the week.
"E", "EE", "EEE" will return abbreviated week day name, e.g. "Tues";
"EEEE" will return full week day name;
"EEEEE" will return the narrow week day name, e.g. "T";

formatDayInYear() method
protected int formatDayInYear(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | int | hours in AM/PM format.

Get the day in the year, e.g. [1-366]

formatEra() method
protected string formatEra(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | era

Get the era. i.e. in gregorian, year > 0 is AD, else BC.

formatHour12() method
protected string formatHour12(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | hours in 12 hour format.

Get the hours in 12 hour format, i.e., [1-12] "h" for non-padding, "hh" will always return 2 characters.

formatHour24() method
protected string formatHour24(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | hours in 24 hour format.

Get the hours in 24 hour format, i.e. [0-23]. "H" for non-padding, "HH" will always return 2 characters.

formatHourInDay() method
protected int formatHourInDay(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | int | hours [1-24]

Get the hours [1-24]. 'k' for non-padding, and 'kk' with 2 characters padding.

formatHourInPeriod() method
protected int formatHourInPeriod(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | int | hours in AM/PM format.

Get the hours in AM/PM format, e.g [0-11] "K" for non-padding, "KK" will always return 2 characters.

formatMinutes() method
protected string formatMinutes(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | minutes.

Get the minutes. "m" for non-padding, "mm" will always return 2 characters.

formatMonth() method
protected string formatMonth(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | month name

Get the month.
"M" will return integer 1 through 12;
"MM" will return two digits month number with necessary zero padding, e.g. 05;
"MMM" will return the abrreviated month name, e.g. "Jan";
"MMMM" will return the full month name, e.g. "January";
"MMMMM" will return the narrow month name, e.g. "J";

formatPeriod() method
protected string formatPeriod(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | AM or PM designator

Get the AM/PM designator, 12 noon is PM, 12 midnight is AM.

formatSeconds() method
protected string formatSeconds(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | seconds

Get the seconds. "s" for non-padding, "ss" will always return 2 characters.

formatTimeZone() method
protected string formatTimeZone(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | time zone

Get the timezone of the server machine.

formatWeekInMonth() method
protected int formatWeekInMonth(array $pattern, string $date)
$pattern | array | result of CTimestamp::getdate.
$date | string | a pattern.
{return} | int | week in month

Get week in the month.

formatWeekInYear() method
protected int formatWeekInYear(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | int | week in year

Get the week in the year.

formatYear() method
protected string formatYear(string $pattern, array $date)
$pattern | string | a pattern.
$date | array | result of CTimestamp::getdate.
{return} | string | formatted year

Get the year. "yy" will return the last two digits of year. "y...y" will pad the year with 0 in the front, e.g. "yyyyy" will generate "02008" for year 2008.

parseFormat() method
protected array parseFormat(string $pattern)
$pattern | string | the pattern to be parsed
{return} | array | tokenized parsing result

Parses the datetime format pattern.


CDbMessageSource

All Packages | Properties | Methods | Events
Package | system.i18n
Inheritance | class CDbMessageSource » CMessageSource » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CDbMessageSource.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbMessageSource represents a message source that stores translated messages in database.

The database must contain the following two tables:
CREATE TABLE SourceMessage
(
    id INTEGER PRIMARY KEY,
    category VARCHAR(32),
    message TEXT
);
CREATE TABLE Message
(
    id INTEGER,
    language VARCHAR(16),
    translation TEXT,
    PRIMARY KEY (id, language),
    CONSTRAINT FK_Message_SourceMessage FOREIGN KEY (id)
         REFERENCES SourceMessage (id) ON DELETE CASCADE ON UPDATE RESTRICT
);
The 'SourceMessage' table stores the messages to be translated, and the 'Message' table stores the translated messages. The name of these two tables can be customized by setting sourceMessageTable and translatedMessageTable, respectively.

When cachingDuration is set as a positive number, message translations will be cached.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component that is used to cache the messages. | CDbMessageSource
cachingDuration | integer | the time in seconds that the messages can remain valid in cache. | CDbMessageSource
connectionID | string | the ID of the database connection application component. | CDbMessageSource
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
language | string | the language that the source messages are written in. | CMessageSource
sourceMessageTable | string | the name of the source message table. | CDbMessageSource
translatedMessageTable | string | the name of the translated message table. | CDbMessageSource

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getLanguage() |  | CMessageSource
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CDbMessageSource
onMissingTranslation() | Raised when a message cannot be translated. | CMessageSource
raiseEvent() | Raises an event. | CComponent
setLanguage() |  | CMessageSource
translate() | Translates a message to the specified language. | CMessageSource

Protected Methods

Hide inherited methods

Method | Description | Defined By
loadMessages() | Loads the message translation for the specified language and category. | CDbMessageSource
translateMessage() | Translates the specified message. | CMessageSource

Events

Hide inherited events

Event | Description | Defined By
onMissingTranslation | Raised when a message cannot be translated. | CMessageSource

Property Details

cacheID property (available since v1.0.10)
public string $cacheID;

the ID of the cache application component that is used to cache the messages. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching the messages.

cachingDuration property
public integer $cachingDuration;

the time in seconds that the messages can remain valid in cache. Defaults to 0, meaning the caching is disabled.

connectionID property
public string $connectionID;

the ID of the database connection application component. Defaults to 'db'.

sourceMessageTable property
public string $sourceMessageTable;

the name of the source message table. Defaults to 'SourceMessage'.

translatedMessageTable property
public string $translatedMessageTable;

the name of the translated message table. Defaults to 'Message'.

Method Details

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by preprocessing the user request data.

loadMessages() method
protected array loadMessages(string $category, string $language)
$category | string | the message category
$language | string | the target language
{return} | array | the loaded messages

Loads the message translation for the specified language and category.


CGettextMessageSource

All Packages | Properties | Methods | Events
Package | system.i18n
Inheritance | class CGettextMessageSource » CMessageSource » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CGettextMessageSource.php 1678 2010-01-07 21:02:00Z qiang.xue $
CGettextMessageSource represents a message source that is based on GNU Gettext.

Each CGettextMessageSource instance represents the message tranlations for a single domain. And each message category represents a message context in Gettext. Translated messages are stored as either a MO or PO file, depending on the useMoFile property value.

All translations are saved under the basePath directory. Translations in one language are kept as MO or PO files under an individual subdirectory whose name is the language ID. The file name is specified via catalog property, which defaults to 'messages'.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the base path for all translated messages. | CGettextMessageSource
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component that is used to cache the messages. | CGettextMessageSource
cachingDuration | integer | the time in seconds that the messages can remain valid in cache. | CGettextMessageSource
catalog | string | the message catalog name. | CGettextMessageSource
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
language | string | the language that the source messages are written in. | CMessageSource
useBigEndian | boolean | whether to use Big Endian to read and write MO files. | CGettextMessageSource
useMoFile | boolean | whether to load messages from MO files. | CGettextMessageSource

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getLanguage() |  | CMessageSource
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CGettextMessageSource
onMissingTranslation() | Raised when a message cannot be translated. | CMessageSource
raiseEvent() | Raises an event. | CComponent
setLanguage() |  | CMessageSource
translate() | Translates a message to the specified language. | CMessageSource

Protected Methods

Hide inherited methods

Method | Description | Defined By
loadMessages() | Loads the message translation for the specified language and category. | CGettextMessageSource
translateMessage() | Translates the specified message. | CMessageSource

Events

Hide inherited events

Event | Description | Defined By
onMissingTranslation | Raised when a message cannot be translated. | CMessageSource

Property Details

basePath property
public string $basePath;

the base path for all translated messages. Defaults to null, meaning the "messages" subdirectory of the application directory (e.g. "protected/messages").

cacheID property (available since v1.0.10)
public string $cacheID;

the ID of the cache application component that is used to cache the messages. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching the messages.

cachingDuration property
public integer $cachingDuration;

the time in seconds that the messages can remain valid in cache. Defaults to 0, meaning the caching is disabled.

catalog property
public string $catalog;

the message catalog name. This is the name of the message file (without extension) that stores the translated messages. Defaults to 'messages'.

useBigEndian property
public boolean $useBigEndian;

whether to use Big Endian to read and write MO files. Defaults to false. This property is only used when useMoFile is true.

useMoFile property
public boolean $useMoFile;

whether to load messages from MO files. Defaults to true. If false, messages will be loaded from PO files.

Method Details

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by preprocessing the user request data.

loadMessages() method
protected array loadMessages(string $category, string $language)
$category | string | the message category
$language | string | the target language
{return} | array | the loaded messages

Loads the message translation for the specified language and category.


CLocale

Package | system.i18n
Inheritance | class CLocale » CComponent
Since | 1.0
Version | $Id: CLocale.php 1843 2010-02-26 15:10:50Z qiang.xue $
CLocale represents the data relevant to a locale.

The data includes the number formatting information and date formatting information.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
aMName | string | the AM name | CLocale
currencyFormat | string | the currency format | CLocale
dataPath | string | the directory that contains the locale data. | CLocale
dateFormat | string | date format | CLocale
dateFormatter | CDateFormatter | the date formatter for this locale | CLocale
dateTimeFormat | string | datetime format, i. | CLocale
decimalFormat | string | the decimal format | CLocale
id | string | the locale ID (in canonical form) | CLocale
monthNames | array | Returns the month names in the specified width. | CLocale
numberFormatter | CNumberFormatter | the number formatter for this locale | CLocale
pMName | string | the PM name | CLocale
percentFormat | string | the percent format | CLocale
scientificFormat | string | the scientific format | CLocale
timeFormat | string | date format | CLocale
weekDayNames | array | Returns the week day names in the specified width. | CLocale

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getAMName() |  | CLocale
getCanonicalID() | Converts a locale ID to its canonical form. | CLocale
getCurrencyFormat() |  | CLocale
getCurrencySymbol() |  | CLocale
getDateFormat() |  | CLocale
getDateFormatter() |  | CLocale
getDateTimeFormat() |  | CLocale
getDecimalFormat() |  | CLocale
getEraName() |  | CLocale
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CLocale
getInstance() | Returns the instance of the specified locale. | CLocale
getLocaleIDs() |  | CLocale
getMonthName() |  | CLocale
getMonthNames() | Returns the month names in the specified width. | CLocale
getNumberFormatter() |  | CLocale
getNumberSymbol() |  | CLocale
getPMName() |  | CLocale
getPercentFormat() |  | CLocale
getScientificFormat() |  | CLocale
getTimeFormat() |  | CLocale
getWeekDayName() |  | CLocale
getWeekDayNames() | Returns the week day names in the specified width. | CLocale
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CLocale

Property Details

aMName property read-only
public string getAMName()

the AM name

currencyFormat property read-only
public string getCurrencyFormat()

the currency format

dataPath property (available since v1.1.0)
public static string $dataPath;

the directory that contains the locale data. If this property is not set, the locale data will be loaded from 'framework/i18n/data'.

dateFormat property read-only
public string getDateFormat(string $width='medium')

date format

dateFormatter property read-only
public CDateFormatter getDateFormatter()

the date formatter for this locale

dateTimeFormat property read-only
public string getDateTimeFormat()

datetime format, i.e., the order of date and time.

decimalFormat property read-only
public string getDecimalFormat()

the decimal format

id property read-only
public string getId()

the locale ID (in canonical form)

monthNames property read-only (available since v1.0.9)
public array getMonthNames(string $width='wide', boolean $standAlone=false)

Returns the month names in the specified width.

numberFormatter property read-only
public CNumberFormatter getNumberFormatter()

the number formatter for this locale

pMName property read-only
public string getPMName()

the PM name

percentFormat property read-only
public string getPercentFormat()

the percent format

scientificFormat property read-only
public string getScientificFormat()

the scientific format

timeFormat property read-only
public string getTimeFormat(string $width='medium')

date format

weekDayNames property read-only (available since v1.0.9)
public array getWeekDayNames(string $width='wide', boolean $standAlone=false)

Returns the week day names in the specified width.

Method Details

__construct() method
protected void __construct(string $id)
$id string the locale ID (e.g. en_US)

Constructor. Since the constructor is protected, please use getInstance to obtain an instance of the specified locale.

getAMName() method
public string getAMName()
{return} string the AM name

getCanonicalID() method
public static string getCanonicalID(string $id)
$id | string | the locale ID to be converted
{return} | string | the locale ID in canonical form

Converts a locale ID to its canonical form. In canonical form, a locale ID consists of only underscores and lower-case letters.

getCurrencyFormat() method
public string getCurrencyFormat()
{return} string the currency format

getCurrencySymbol() method
public string getCurrencySymbol(string $currency)
$currency | string | 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
{return} | string | the localized currency symbol. Null if the symbol does not exist.

getDateFormat() method
public string getDateFormat(string $width='medium')
$width | string | date format width. It can be 'full', 'long', 'medium' or 'short'.
{return} | string | date format

getDateFormatter() method
public CDateFormatter getDateFormatter()
{return} CDateFormatter the date formatter for this locale

getDateTimeFormat() method
public string getDateTimeFormat()
{return} string datetime format, i.e., the order of date and time.

getDecimalFormat() method
public string getDecimalFormat()
{return} string the decimal format

getEraName() method
public string getEraName(integer $era, string $width='wide')
$era | integer | era (0,1)
$width | string | era name width. It can be 'wide', 'abbreviated' or 'narrow'.
{return} | string | the era name

getId() method
public string getId()
{return} string the locale ID (in canonical form)

getInstance() method
public static CLocale getInstance(string $id)
$id | string | the locale ID (e.g. en_US)
{return} | CLocale | the locale instance

Returns the instance of the specified locale. Since the constructor of CLocale is protected, you can only use this method to obtain an instance of the specified locale.

getLocaleIDs() method
public static array getLocaleIDs()
{return} array IDs of the locales which the framework can recognize

getMonthName() method
public string getMonthName(integer $month, string $width='wide', boolean $standAlone=false)
$month | integer | month (1-12)
$width | string | month name width. It can be 'wide', 'abbreviated' or 'narrow'.
$standAlone | boolean | whether the month name should be returned in stand-alone format
{return} | string | the month name

getMonthNames() method (available since v1.0.9)
public array getMonthNames(string $width='wide', boolean $standAlone=false)
$width | string | month name width. It can be 'wide', 'abbreviated' or 'narrow'.
$standAlone | boolean | whether the month names should be returned in stand-alone format
{return} | array | month names indexed by month values (1-12)

Returns the month names in the specified width.

getNumberFormatter() method
public CNumberFormatter getNumberFormatter()
{return} CNumberFormatter the number formatter for this locale

getNumberSymbol() method
public string getNumberSymbol(string $name)
$name | string | symbol name
{return} | string | symbol

getPMName() method
public string getPMName()
{return} string the PM name

getPercentFormat() method
public string getPercentFormat()
{return} string the percent format

getScientificFormat() method
public string getScientificFormat()
{return} string the scientific format

getTimeFormat() method
public string getTimeFormat(string $width='medium')
$width | string | time format width. It can be 'full', 'long', 'medium' or 'short'.
{return} | string | date format

getWeekDayName() method
public string getWeekDayName(integer $day, string $width='wide', boolean $standAlone=false)
$day | integer | weekday (0-6, 0 means Sunday)
$width | string | weekday name width. It can be 'wide', 'abbreviated' or 'narrow'.
$standAlone | boolean | whether the week day name should be returned in stand-alone format
{return} | string | the weekday name

getWeekDayNames() method (available since v1.0.9)
public array getWeekDayNames(string $width='wide', boolean $standAlone=false)
$width | string | weekday name width. It can be 'wide', 'abbreviated' or 'narrow'.
$standAlone | boolean | whether the week day name should be returned in stand-alone format
{return} | array | the weekday names indexed by weekday values (0-6, 0 means Sunday, 1 Monday, etc.)

Returns the week day names in the specified width.


CMessageSource

All Packages | Properties | Methods | Events
Package | system.i18n
Inheritance | abstract class CMessageSource » CApplicationComponent » CComponent
Implements | IApplicationComponent
Subclasses | CDbMessageSource, CGettextMessageSource, CPhpMessageSource
Since | 1.0
Version | $Id: CMessageSource.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMessageSource is the base class for message translation repository classes.

A message source is an application component that provides message internationalization (i18n). It stores messages translated in different languages and provides these translated versions when requested.

A concrete class must implement loadMessages or override translateMessage.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
language | string | the language that the source messages are written in. | CMessageSource

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getLanguage() |  | CMessageSource
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
onMissingTranslation() | Raised when a message cannot be translated. | CMessageSource
raiseEvent() | Raises an event. | CComponent
setLanguage() |  | CMessageSource
translate() | Translates a message to the specified language. | CMessageSource

Protected Methods

Hide inherited methods

Method | Description | Defined By
loadMessages() | Loads the message translation for the specified language and category. | CMessageSource
translateMessage() | Translates the specified message. | CMessageSource

Events

Hide inherited events

Event | Description | Defined By
onMissingTranslation | Raised when a message cannot be translated. | CMessageSource

Property Details

language property
public string getLanguage()
public void setLanguage(string $language)

the language that the source messages are written in. Defaults to application language.

Method Details

getLanguage() method
public string getLanguage()
{return} string the language that the source messages are written in. Defaults to application language.

loadMessages() method
abstract protected array loadMessages(string $category, string $language)
$category | string | the message category
$language | string | the target language
{return} | array | the loaded messages

Loads the message translation for the specified language and category.

onMissingTranslation() method
public void onMissingTranslation(CMissingTranslationEvent $event)
$event CMissingTranslationEvent the event parameter

Raised when a message cannot be translated. Handlers may log this message or do some default handling. The CMissingTranslationEvent::message property will be returned by translateMessage.

setLanguage() method
public void setLanguage(string $language)
$language string the language that the source messages are written in.

translate() method
public string translate(string $category, string $message, string $language=NULL)
$category | string | the message category
$message | string | the message to be translated
$language | string | the target language. If null (default), the application language will be used. This parameter has been available since version 1.0.3.
{return} | string | the translated message (or the original message if translation is not needed)

Translates a message to the specified language.

Note, if the specified language is the same as the source message language, messages will NOT be translated.

If the message is not found in the translations, an onMissingTranslation event will be raised. Handlers can mark this message or do some default handling. The CMissingTranslationEvent::message property of the event parameter will be returned.

translateMessage() method
protected string translateMessage(string $category, string $message, string $language)
$category | string | the category that the message belongs to
$message | string | the message to be translated
$language | string | the target language
{return} | string | the translated message

Translates the specified message. If the message is not found, an onMissingTranslation event will be raised.


CMissingTranslationEvent

Package | system.i18n
Inheritance | class CMissingTranslationEvent » CEvent » CComponent
Since | 1.0
Version | $Id: CMessageSource.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMissingTranslationEvent represents the parameter for the onMissingTranslation event.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
category | string | the category that the message belongs to | CMissingTranslationEvent
handled | boolean | whether the event is handled. | CEvent
language | string | the ID of the language that the message is to be translated to | CMissingTranslationEvent
message | string | the message to be translated | CMissingTranslationEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CMissingTranslationEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

category property
public string $category;

the category that the message belongs to

language property
public string $language;

the ID of the language that the message is to be translated to

message property
public string $message;

the message to be translated

Method Details

__construct() method
public void __construct(mixed $sender, string $category, string $message, string $language)
$sender | mixed | sender of this event
$category | string | the category that the message belongs to
$message | string | the message to be translated
$language | string | the ID of the language that the message is to be translated to

Constructor.


CNumberFormatter

All Packages | Methods
Package | system.i18n
Inheritance | class CNumberFormatter » CComponent
Since | 1.0
Version | $Id: CNumberFormatter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CNumberFormatter provides number localization functionalities.

CNumberFormatter formats a number (integer or double) and outputs a string based on the specified format. A CNumberFormatter instance is associated with a locale, and thus generates the string representation of the number in a locale-dependent fashion.

CNumberFormatter currently supports currency format, percentage format, decimal format, and custom format. The first three formats are specified in the locale data, while the custom format allows you to enter an arbitrary format string.

A format string may consist of the following special characters:
  • dot (.): the decimal point. It will be replaced with the localized decimal point.
  • comma (,): the grouping separator. It will be replaced with the localized grouping separator.
  • zero (0): required digit. This specifies the places where a digit must appear (will pad 0 if not).
  • hash (#): optional digit. This is mainly used to specify the location of decimal point and grouping separators.
  • currency (¤): the currency placeholder. It will be replaced with the localized currency symbol.
  • percentage (%): the percetage mark. If appearing, the number will be multiplied by 100 before being formatted.
  • permillage (‰): the permillage mark. If appearing, the number will be multiplied by 1000 before being formatted.
  • semicolon (;): the character separating positive and negative number sub-patterns.

Anything surrounding the pattern (or sub-patterns) will be kept.

The followings are some examples:
Pattern "#,##0.00" will format 12345.678 as "12,345.68".
Pattern "#,#,#0.00" will format 12345.6 as "1,2,3,45.60".
Note, in the first example, the number is rounded first before applying the formatting. And in the second example, the pattern specifies two grouping sizes.

CNumberFormatter attempts to implement number formatting according to the Unicode Technical Standard #35. The following features are NOT implemented:
  • significant digit
  • scientific format
  • arbitrary literal characters
  • arbitrary padding

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CNumberFormatter
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
format() | Formats a number based on the specified pattern. | CNumberFormatter
formatCurrency() | Formats a number using the currency format defined in the locale. | CNumberFormatter
formatDecimal() | Formats a number using the decimal format defined in the locale. | CNumberFormatter
formatPercentage() | Formats a number using the percentage format defined in the locale. | CNumberFormatter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatNumber() | Formats a number based on a format. | CNumberFormatter
parseFormat() | Parses a given string pattern. | CNumberFormatter

Method Details

__construct() method
public void __construct(mixed $locale)
$locale mixed locale ID (string) or CLocale instance

Constructor.

format() method
public string format(string $pattern, mixed $value, string $currency=NULL)
$pattern | string | format pattern
$value | mixed | the number to be formatted
$currency | string | 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency. The currency placeholder in the pattern will be replaced with the currency symbol. If null, no replacement will be done.
{return} | string | the formatting result.

Formats a number based on the specified pattern. Note, if the format contains '%', the number will be multiplied by 100 first. If the format contains '‰', the number will be multiplied by 1000. If the format contains currency placeholder, it will be replaced by the specified localized currency symbol.

formatCurrency() method
public string formatCurrency(mixed $value, string $currency)
$value | mixed | the number to be formatted
$currency | string | 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency. The currency placeholder in the pattern will be replaced with the currency symbol.
{return} | string | the formatting result.

Formats a number using the currency format defined in the locale.

formatDecimal() method
public string formatDecimal(mixed $value)
$value | mixed | the number to be formatted
{return} | string | the formatting result.

Formats a number using the decimal format defined in the locale.

formatNumber() method
protected string formatNumber(array $format, mixed $value)
$format array format with the following structure:
array(
    'decimalDigits'=>2,     // number of required digits after decimal point; 0s will be padded if not enough digits; if -1, it means we should drop decimal point
 'maxDecimalDigits'=>3,  // maximum number of digits after decimal point. Additional digits will be truncated.
    'integerDigits'=>1,     // number of required digits before decimal point; 0s will be padded if not enough digits
    'groupSize1'=>3,        // the primary grouping size; if 0, it means no grouping
    'groupSize2'=>0,        // the secondary grouping size; if 0, it means no secondary grouping
    'positivePrefix'=>'+',  // prefix to positive number
    'positiveSuffix'=>'',   // suffix to positive number
    'negativePrefix'=>'(',  // prefix to negative number
    'negativeSuffix'=>')',  // suffix to negative number
    'multiplier'=>1,        // 100 for percent, 1000 for per mille
);
$value | mixed | the number to be formatted
{return} | string | the formatted result

Formats a number based on a format. This is the method that does actual number formatting.

formatPercentage() method
public string formatPercentage(mixed $value)
$value | mixed | the number to be formatted
{return} | string | the formatting result.

Formats a number using the percentage format defined in the locale. Note, if the percentage format contains '%', the number will be multiplied by 100 first. If the percentage format contains '‰', the number will be multiplied by 1000.

parseFormat() method
protected array parseFormat(string $pattern)
$pattern | string | the pattern to be parsed
{return} | array | the parsed pattern

Parses a given string pattern.

See Also

  • formatNumber


CPhpMessageSource

All Packages | Properties | Methods | Events
Package | system.i18n
Inheritance | class CPhpMessageSource » CMessageSource » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CPhpMessageSource.php 1884 2010-03-11 14:58:33Z qiang.xue $
CPhpMessageSource represents a message source that stores translated messages in PHP scripts.

CPhpMessageSource uses PHP files and arrays to keep message translations.
  • All translations are saved under the basePath directory.
  • Translations in one language are kept as PHP files under an individual subdirectory whose name is the same as the language ID. Each PHP file contains messages belonging to the same category, and the file name is the same as the category name.
  • Within a PHP file, an array of (source, translation) pairs is returned. For example:
    return array(
    'original message 1' => 'translated message 1',
    'original message 2' => 'translated message 2',
);
When cachingDuration is set as a positive number, message translations will be cached.

Starting from version 1.0.10, messages for an extension class (e.g. a widget, a module) can be specially managed and used. In particular, if a message belongs to an extension whose class name is Xyz, then the message category can be specified in the format of 'Xyz.categoryName'. And the corresponding message file is assumed to be 'BasePath/messages/LanguageID/categoryName.php', where 'BasePath' refers to the directory that contains the extension class file. When using Yii::t() to translate an extension message, the category name should be set as 'Xyz.categoryName'.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the base path for all translated messages. | CPhpMessageSource
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component that is used to cache the messages. | CPhpMessageSource
cachingDuration | integer | the time in seconds that the messages can remain valid in cache. | CPhpMessageSource
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
language | string | the language that the source messages are written in. | CMessageSource

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getLanguage() |  | CMessageSource
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CPhpMessageSource
onMissingTranslation() | Raised when a message cannot be translated. | CMessageSource
raiseEvent() | Raises an event. | CComponent
setLanguage() |  | CMessageSource
translate() | Translates a message to the specified language. | CMessageSource

Protected Methods

Hide inherited methods

Method | Description | Defined By
getMessageFile() | Determines the message file name based on the given category and language. | CPhpMessageSource
loadMessages() | Loads the message translation for the specified language and category. | CPhpMessageSource
translateMessage() | Translates the specified message. | CMessageSource

Events

Hide inherited events

Event | Description | Defined By
onMissingTranslation | Raised when a message cannot be translated. | CMessageSource

Property Details

basePath property
public string $basePath;

the base path for all translated messages. Defaults to null, meaning the "messages" subdirectory of the application directory (e.g. "protected/messages").

cacheID property (available since v1.0.10)
public string $cacheID;

the ID of the cache application component that is used to cache the messages. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching the messages.

cachingDuration property
public integer $cachingDuration;

the time in seconds that the messages can remain valid in cache. Defaults to 0, meaning the caching is disabled.

Method Details

getMessageFile() method (available since v1.0.10)
protected string getMessageFile(string $category, string $language)
$category | string | category name
$language | string | language ID
{return} | string | the message file path

Determines the message file name based on the given category and language. If the category name contains a dot, it will be split into the module class name and the category name. In this case, the message file will be assumed to be located within the 'messages' subdirectory of the directory containing the module class file. Otherwise, the message file is assumed to be under the basePath.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by preprocessing the user request data.

loadMessages() method
protected array loadMessages(string $category, string $language)
$category | string | the message category
$language | string | the target language
{return} | array | the loaded messages

Loads the message translation for the specified language and category.


CGettextFile

All Packages | Methods
Package | system.i18n.gettext
Inheritance | abstract class CGettextFile » CComponent
Subclasses | CGettextMoFile, CGettextPoFile
Since | 1.0
Version | $Id: CGettextFile.php 1678 2010-01-07 21:02:00Z qiang.xue $
CGettextFile is the base class for representing a Gettext message file.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
load() | Loads messages from a file. | CGettextFile
raiseEvent() | Raises an event. | CComponent
save() | Saves messages to a file. | CGettextFile

Method Details

load() method
abstract public array load(string $file, string $context)
$file | string | file path
$context | string | message context
{return} | array | message translations (source message => translated message)

Loads messages from a file.

save() method
abstract public void save(string $file, array $messages)
$file | string | file path
$messages | array | message translations (message id => translated message). Note if the message has a context, the message id must be prefixed with the context with chr(4) as the separator.

Saves messages to a file.


CGettextMoFile

Package | system.i18n.gettext
Inheritance | class CGettextMoFile » CGettextFile » CComponent
Since | 1.0
Version | $Id: CGettextMoFile.php 1678 2010-01-07 21:02:00Z qiang.xue $
CGettextMoFile represents an MO Gettext message file.

This class is written by adapting Michael's Gettext_MO class in PEAR. Please refer to the following license terms.

Copyright (c) 2004-2005, Michael Wallner . All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
useBigEndian | boolean | whether to use Big Endian when reading and writing an integer. | CGettextMoFile

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGettextMoFile
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
load() | Loads messages from an MO file. | CGettextMoFile
raiseEvent() | Raises an event. | CComponent
save() | Saves messages to an MO file. | CGettextMoFile

Protected Methods

Hide inherited methods

Method | Description | Defined By
readByte() | Reads one or several bytes. | CGettextMoFile
readInteger() | Reads a 4-byte integer. | CGettextMoFile
readString() | Reads a string. | CGettextMoFile
writeByte() | Writes bytes. | CGettextMoFile
writeInteger() | Writes a 4-byte integer. | CGettextMoFile
writeString() | Writes a string. | CGettextMoFile

Property Details

useBigEndian property
public boolean $useBigEndian;

whether to use Big Endian when reading and writing an integer.

Method Details

__construct() method
public void __construct(boolean $useBigEndian=false)
$useBigEndian boolean whether to use Big Endian when reading and writing an integer.

Constructor.

load() method
public array load(string $file, string $context)
$file | string | file path
$context | string | message context
{return} | array | message translations (source message => translated message)

Loads messages from an MO file.

readByte() method
protected string readByte(resource $fr, integer $n=1)
$fr | resource | file handle
$n | integer | number of bytes to read
{return} | string | bytes

Reads one or several bytes.

readInteger() method
protected integer readInteger(resource $fr)
$fr | resource | file handle
{return} | integer | the result

Reads a 4-byte integer.

See Also

  • useBigEndian
readString() method
protected string readString(resource $fr, integer $length, integer $offset=NULL)
$fr | resource | file handle
$length | integer | string length
$offset | integer | offset of the string in the file. If null, it reads from the current position.
{return} | string | the result

Reads a string.

save() method
public void save(string $file, array $messages)
$file | string | file path
$messages | array | message translations (message id => translated message). Note if the message has a context, the message id must be prefixed with the context with chr(4) as the separator.

Saves messages to an MO file.

writeByte() method
protected integer writeByte(resource $fw, string $data)
$fw | resource | file handle
$data | string | the data
{return} | integer | how many bytes are written

Writes bytes.

writeInteger() method
protected integer writeInteger(resource $fw, integer $data)
$fw | resource | file handle
$data | integer | the data
{return} | integer | how many bytes are written

Writes a 4-byte integer.

writeString() method
protected integer writeString(resource $fw, string $data)
$fw | resource | file handle
$data | string | the string
{return} | integer | how many bytes are written

Writes a string.


CGettextPoFile

All Packages | Methods
Package | system.i18n.gettext
Inheritance | class CGettextPoFile » CGettextFile » CComponent
Since | 1.0
Version | $Id: CGettextPoFile.php 1845 2010-02-27 01:11:45Z qiang.xue $
CGettextPoFile represents a PO Gettext message file.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
load() | Loads messages from a PO file. | CGettextPoFile
raiseEvent() | Raises an event. | CComponent
save() | Saves messages to a PO file. | CGettextPoFile

Protected Methods

Hide inherited methods

Method | Description | Defined By
decode() | Decodes special characters in a message. | CGettextPoFile
encode() | Encodes special characters in a message. | CGettextPoFile

Method Details

decode() method
protected string decode(string $string)
$string | string | message to be decoded
{return} | string | the decoded message

Decodes special characters in a message.

encode() method
protected string encode(string $string)
$string | string | message to be encoded
{return} | string | the encoded message

Encodes special characters in a message.

load() method
public array load(string $file, string $context)
$file | string | file path
$context | string | message context
{return} | array | message translations (source message => translated message)

Loads messages from a PO file.

save() method
public void save(string $file, array $messages)
$file | string | file path
$messages | array | message translations (message id => translated message). Note if the message has a context, the message id must be prefixed with the context with chr(4) as the separator.

Saves messages to a PO file.


CDbLogRoute

Package | system.logging
Inheritance | class CDbLogRoute » CLogRoute » CComponent
Since | 1.0
Version | $Id: CDbLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbLogRoute stores log messages in a database table.

To specify the database table for storing log messages, set logTableName as the name of the table and specify connectionID to be the ID of a CDbConnection application component. If they are not set, a SQLite3 database named 'log-YiiVersion.db' will be created and used under the application runtime directory.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoCreateLogTable | boolean | whether the log DB table should be automatically created if not exists. | CDbLogRoute
categories | string | list of categories separated by comma or space. | CLogRoute
connectionID | string | the ID of CDbConnection application component. | CDbLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logTableName | string | the name of the DB table that stores log content. | CDbLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | the DB connection instance | CDbLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__destruct() | Destructor. | CDbLogRoute
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CDbLogRoute
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
createLogTable() | Creates the DB table for storing log messages. | CDbLogRoute
formatLogMessage() | Formats a log message given different fields. | CLogRoute
getDbConnection() |  | CDbLogRoute
processLogs() | Stores log messages into database. | CDbLogRoute

Property Details

autoCreateLogTable property
public boolean $autoCreateLogTable;

whether the log DB table should be automatically created if not exists. Defaults to true.

See Also

  • logTableName
connectionID property
public string $connectionID;

the ID of CDbConnection application component. If not set, a SQLite database will be automatically created and used. The SQLite database file is protected/runtime/log-YiiVersion.db.

dbConnection property read-only
protected CDbConnection getDbConnection()

the DB connection instance

logTableName property
public string $logTableName;

the name of the DB table that stores log content. Defaults to 'YiiLog'. If autoCreateLogTable is false and you want to create the DB table manually by yourself, you need to make sure the DB table is of the following structure:

 (
    id       INTEGER NOT NULL PRIMARY KEY,
    level    VARCHAR(128),
    category VARCHAR(128),
    logtime  INTEGER,
    message  TEXT
  )
Note, the 'id' column must be created as an auto-incremental column. In MySQL, this means it should be id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY; In PostgreSQL, it is id SERIAL PRIMARY KEY.

See Also

  • autoCreateLogTable

Method Details

__destruct() method
public void __destruct()

Destructor. Disconnect the db connection.

createLogTable() method
protected void createLogTable(CDbConnection $db, string $tableName)
$db | CDbConnection | the database connection
$tableName | string | the name of the table to be created

Creates the DB table for storing log messages.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance

init() method
public void init()

Initializes the route. This method is invoked after the route is created by the route manager.

processLogs() method
protected void processLogs(array $logs)
$logs array list of log messages

Stores log messages into database.


CEmailLogRoute

Package | system.logging
Inheritance | class CEmailLogRoute » CLogRoute » CComponent
Since | 1.0
Version | $Id: CEmailLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CEmailLogRoute sends selected log messages to email addresses.

The target email addresses may be specified via emails property. Optionally, you may set the email subject and the sentFrom address.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
categories | string | list of categories separated by comma or space. | CLogRoute
emails | array | list of destination email addresses | CEmailLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute
sentFrom | string | send from address of the email | CEmailLogRoute
subject | string | email subject. | CEmailLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEmails() |  | CEmailLogRoute
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getSentFrom() |  | CEmailLogRoute
getSubject() |  | CEmailLogRoute
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CLogRoute
raiseEvent() | Raises an event. | CComponent
setEmails() |  | CEmailLogRoute
setSentFrom() |  | CEmailLogRoute
setSubject() |  | CEmailLogRoute

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatLogMessage() | Formats a log message given different fields. | CLogRoute
processLogs() | Sends log messages to specified email addresses. | CEmailLogRoute
sendEmail() | Sends an email. | CEmailLogRoute

Property Details

emails property
public array getEmails()
public array|string setEmails($value)

list of destination email addresses

sentFrom property
public string getSentFrom()
public void setSentFrom(string $value)

send from address of the email

subject property
public string getSubject()
public void setSubject(string $value)

email subject. Defaults to CEmailLogRoute::DEFAULT_SUBJECT

Method Details

getEmails() method
public array getEmails()
{return} array list of destination email addresses

getSentFrom() method
public string getSentFrom()
{return} string send from address of the email

getSubject() method
public string getSubject()
{return} string email subject. Defaults to CEmailLogRoute::DEFAULT_SUBJECT

processLogs() method
protected void processLogs(array $logs)
$logs array list of log messages

Sends log messages to specified email addresses.

sendEmail() method
protected void sendEmail(string $email, string $subject, string $message)
$email | string | single email address
$subject | string | email subject
$message | string | email content

Sends an email.

setEmails() method
public array|string setEmails($value)
$value |  |
{return} | array|string | list of destination email addresses. If the value is a string, it is assumed to be comma-separated email addresses.

setSentFrom() method
public void setSentFrom(string $value)
$value string send from address of the email

setSubject() method
public void setSubject(string $value)
$value string email subject.


CFileLogRoute

Package | system.logging
Inheritance | class CFileLogRoute » CLogRoute » CComponent
Since | 1.0
Version | $Id: CFileLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFileLogRoute records log messages in files.

The log files are stored under logPath and the file name is specified by logFile. If the size of the log file is greater than maxFileSize (in kilo-bytes), a rotation is performed, which renames the current log file by suffixing the file name with '.1'. All existing log files are moved backwards one place, i.e., '.2' to '.3', '.1' to '.2'. The property maxLogFiles specifies how many files to be kept.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
categories | string | list of categories separated by comma or space. | CLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logFile | string | log file name. | CFileLogRoute
logPath | string | directory storing log files. | CFileLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute
maxFileSize | integer | maximum log file size in kilo-bytes (KB). | CFileLogRoute
maxLogFiles | integer | number of files used for rotation. | CFileLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLogFile() |  | CFileLogRoute
getLogPath() |  | CFileLogRoute
getMaxFileSize() |  | CFileLogRoute
getMaxLogFiles() |  | CFileLogRoute
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CFileLogRoute
raiseEvent() | Raises an event. | CComponent
setLogFile() |  | CFileLogRoute
setLogPath() |  | CFileLogRoute
setMaxFileSize() |  | CFileLogRoute
setMaxLogFiles() |  | CFileLogRoute

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatLogMessage() | Formats a log message given different fields. | CLogRoute
processLogs() | Saves log messages in files. | CFileLogRoute
rotateFiles() | Rotates log files. | CFileLogRoute

Property Details

logFile property
public string getLogFile()
public void setLogFile(string $value)

log file name. Defaults to 'application.log'.

logPath property
public string getLogPath()
public void setLogPath(string $value)

directory storing log files. Defaults to application runtime path.

maxFileSize property
public integer getMaxFileSize()
public void setMaxFileSize(integer $value)

maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB).

maxLogFiles property
public integer getMaxLogFiles()
public void setMaxLogFiles(integer $value)

number of files used for rotation. Defaults to 5.

Method Details

getLogFile() method
public string getLogFile()
{return} string log file name. Defaults to 'application.log'.

getLogPath() method
public string getLogPath()
{return} string directory storing log files. Defaults to application runtime path.

getMaxFileSize() method
public integer getMaxFileSize()
{return} integer maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB).

getMaxLogFiles() method
public integer getMaxLogFiles()
{return} integer number of files used for rotation. Defaults to 5.

init() method
public void init()

Initializes the route. This method is invoked after the route is created by the route manager.

processLogs() method
protected void processLogs(array $logs)
$logs array list of log messages

Saves log messages in files.

rotateFiles() method
protected void rotateFiles()

Rotates log files.

setLogFile() method
public void setLogFile(string $value)
$value string log file name

setLogPath() method
public void setLogPath(string $value)
$value string directory for storing log files.

setMaxFileSize() method
public void setMaxFileSize(integer $value)
$value integer maximum log file size in kilo-bytes (KB).

setMaxLogFiles() method
public void setMaxLogFiles(integer $value)
$value integer number of files used for rotation.


CLogFilter

Package | system.logging
Inheritance | class CLogFilter » CComponent
Since | 1.0.6
Version | $Id: CLogFilter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CLogFilter preprocesses the logged messages before they are handled by a log route.

CLogFilter is meant to be used by a log route to preprocess the logged messages before they are handled by the route. The default implementation of CLogFilter prepends additional context information to the logged messages. In particular, by setting logVars, predefined PHP variables such as $_SERVER, $_POST, etc. can be saved as a log message, which may help identify/debug issues encountered.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
logUser | boolean | whether to log the current user name and ID. | CLogFilter
logVars | array | list of the PHP predefined variables that should be logged. | CLogFilter
prefixSession | boolean | whether to prefix each log message with the current user session ID. | CLogFilter
prefixUser | boolean | whether to prefix each log message with the current user name and ID. | CLogFilter

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
context | string | Generates the context information to be logged. | CLogFilter

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Filters the given log messages. | CLogFilter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
format() | Formats the log messages. | CLogFilter
getContext() | Generates the context information to be logged. | CLogFilter

Property Details

context property read-only
protected string getContext()

Generates the context information to be logged. The default implementation will dump user information, system variables, etc.

logUser property
public boolean $logUser;

whether to log the current user name and ID. Defaults to true. This property is effective only when showContext is true.

logVars property
public array $logVars;

list of the PHP predefined variables that should be logged. Note that a variable must be accessible via $GLOBALS. Otherwise it won't be logged.

prefixSession property
public boolean $prefixSession;

whether to prefix each log message with the current user session ID. Defaults to false.

prefixUser property
public boolean $prefixUser;

whether to prefix each log message with the current user name and ID. Defaults to false.

Method Details

filter() method
public void filter(array $logs)
$logs array the log messages

Filters the given log messages. This is the main method of CLogFilter. It processes the log messages by adding context information, etc.

format() method
protected void format($logs)
$logs

Formats the log messages. The default implementation will prefix each message with session ID if prefixSession is set true. It may also prefix each message with the current user's name and ID if prefixUser is true.

getContext() method
protected string getContext()
{return} string the context information. If an empty string, it means no context information.

Generates the context information to be logged. The default implementation will dump user information, system variables, etc.


CLogRoute

Package | system.logging
Inheritance | abstract class CLogRoute » CComponent
Subclasses | CDbLogRoute, CEmailLogRoute, CFileLogRoute, CWebLogRoute
Since | 1.0
Version | $Id: CLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CLogRoute is the base class for all log route classes.

A log route object retrieves log messages from a logger and sends it somewhere, such as files, emails. The messages being retrieved may be filtered first before being sent to the destination. The filters include log level filter and log category filter.

To specify level filter, set levels property, which takes a string of comma-separated desired level names (e.g. 'Error, Debug'). To specify category filter, set categories property, which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO').

Level filter and category filter are combinational, i.e., only messages satisfying both filter conditions will they be returned.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
categories | string | list of categories separated by comma or space. | CLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CLogRoute
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatLogMessage() | Formats a log message given different fields. | CLogRoute
processLogs() | Processes log messages and sends them to specific destination. | CLogRoute

Property Details

categories property
public string $categories;

list of categories separated by comma or space. Defaults to empty, meaning all categories.

enabled property (available since v1.0.7)
public boolean $enabled;

whether to enable this log route. Defaults to true.

filter property (available since v1.0.6)
public mixed $filter;

the additional filter (e.g. CLogFilter) that can be applied to the log messages. The value of this property will be passed to Yii::createComponent to create a log filter object. As a result, this can be either a string representing the filter class name or an array representing the filter configuration. In general, the log filter class should be CLogFilter or a child class of it. Defaults to null, meaning no filter will be used.

levels property
public string $levels;

list of levels separated by comma or space. Defaults to empty, meaning all levels.

logs property (available since v1.1.0)
public array $logs;

the logs that are collected so far by this log route.

Method Details

collectLogs() method
public void collectLogs(CLogger $logger, boolean $processLogs=false)
$logger | CLogger | logger instance
$processLogs | boolean | whether to process the logs after they are collected from the logger

Retrieves filtered log messages from logger for further processing.

formatLogMessage() method
protected string formatLogMessage(string $message, integer $level, string $category, integer $time)
$message | string | message content
$level | integer | message level
$category | string | message category
$time | integer | timestamp
{return} | string | formatted message

Formats a log message given different fields.

init() method
public void init()

Initializes the route. This method is invoked after the route is created by the route manager.

processLogs() method
abstract protected void processLogs(array $logs)
$logs array list of messages. Each array elements represents one message with the following structure: array( [0] => message (string) [1] => level (string) [2] => category (string) [3] => timestamp (float, obtained by microtime(true));

Processes log messages and sends them to specific destination. Derived child classes must implement this method.


CLogRouter

Package | system.logging
Inheritance | class CLogRouter » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CLogRouter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CLogRouter manages log routes that record log messages in different media.

For example, a file log route CFileLogRoute records log messages in log files. An email log route CEmailLogRoute sends log messages to specific email addresses. See CLogRoute for more details about different log routes.

Log routes may be configured in application configuration like following:
array(
    'preload'=>array('log'), // preload log component when app starts
    'components'=>array(
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'trace, info',
                    'categories'=>'system.*',
                ),
                array(
                    'class'=>'CEmailLogRoute',
                    'levels'=>'error, warning',
                    'email'=>'admin@example.com',
                ),
            ),
        ),
    ),
)

You can specify multiple routes with different filtering conditions and different targets, even if the routes are of the same type.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
routes | array | the currently initialized routes | CLogRouter

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Collects log messages from a logger. | CLogRouter
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getRoutes() |  | CLogRouter
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CLogRouter
processLogs() | Collects and processes log messages from a logger. | CLogRouter
raiseEvent() | Raises an event. | CComponent
setRoutes() |  | CLogRouter

Property Details

routes property
public array getRoutes()
public void setRoutes(array $config)

the currently initialized routes

Method Details

collectLogs() method
public void collectLogs(CEvent $event)
$event CEvent event parameter

Collects log messages from a logger. This method is an event handler to the CLogger::onFlush event.

getRoutes() method
public array getRoutes()
{return} array the currently initialized routes

init() method
public void init()

Initializes this application component. This method is required by the IApplicationComponent interface.

processLogs() method (available since v1.1.0)
public void processLogs(CEvent $event)
$event CEvent event parameter

Collects and processes log messages from a logger. This method is an event handler to the CApplication::onEndRequest event.

setRoutes() method
public void setRoutes(array $config)
$config array list of route configurations. Each array element represents the configuration for a single route and has the following array structure:
  • class: specifies the class name or alias for the route class.
  • name-value pairs: configure the initial property values of the route.


CLogger

All Packages | Properties | Methods | Events
Package | system.logging
Inheritance | class CLogger » CComponent
Since | 1.0
Version | $Id: CLogger.php 1678 2010-01-07 21:02:00Z qiang.xue $
CLogger records log messages in memory.

CLogger implements the methods to retrieve the messages with various filter conditions, including log levels and log categories.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoFlush | integer | how many messages should be logged before they are flushed to destinations. | CLogger
executionTime | float | Returns the total time for serving the current request. | CLogger
logs | array | Retrieves log messages. | CLogger
memoryUsage | integer | Returns the memory usage of the current application. | CLogger
profilingResults | array | Returns the profiling results. | CLogger

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
flush() | Removes all recorded messages from the memory. | CLogger
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getExecutionTime() | Returns the total time for serving the current request. | CLogger
getLogs() | Retrieves log messages. | CLogger
getMemoryUsage() | Returns the memory usage of the current application. | CLogger
getProfilingResults() | Returns the profiling results. | CLogger
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
log() | Logs a message. | CLogger
onFlush() | Raises an onFlush event. | CLogger
raiseEvent() | Raises an event. | CComponent

Events

Hide inherited events

Event | Description | Defined By
onFlush | Raises an onFlush event. | CLogger

Property Details

autoFlush property (available since v1.1.0)
public integer $autoFlush;

how many messages should be logged before they are flushed to destinations. Defaults to 10,000, meaning for every 10,000 messages, the flush method will be automatically invoked once. If this is 0, it means messages will never be flushed automatically.

executionTime property read-only
public float getExecutionTime()

Returns the total time for serving the current request. This method calculates the difference between now and the timestamp defined by constant YII_BEGIN_TIME. To estimate the execution time more accurately, the constant should be defined as early as possible (best at the beginning of the entry script.)

logs property read-only
public array getLogs(string $levels='', string $categories='')

Retrieves log messages.

Messages may be filtered by log levels and/or categories. A level filter is specified by a list of levels separated by comma or space (e.g. 'trace, error'). A category filter is similar to level filter (e.g. 'system, system.web'). A difference is that in category filter you can use pattern like 'system.*' to indicate all categories starting with 'system'.

If you do not specify level filter, it will bring back logs at all levels. The same applies to category filter.

Level filter and category filter are combinational, i.e., only messages satisfying both filter conditions will be returned.

memoryUsage property read-only
public integer getMemoryUsage()

Returns the memory usage of the current application. This method relies on the PHP function memory_get_usage(). If it is not available, the method will attempt to use OS programs to determine the memory usage. A value 0 will be returned if the memory usage can still not be determined.

profilingResults property read-only (available since v1.0.6)
public array getProfilingResults(string $token=NULL, string $category=NULL, boolean $refresh=false)

Returns the profiling results. The results may be filtered by token and/or category. If no filter is specified, the returned results would be an array with each element being array($token,$category,$time). If a filter is specified, the results would be an array of timings.

Method Details

flush() method (available since v1.1.0)
public void flush()

Removes all recorded messages from the memory. This method will raise an onFlush event. The attached event handlers can process the log messages before they are removed.

getExecutionTime() method
public float getExecutionTime()
{return} float the total time for serving the current request.

Returns the total time for serving the current request. This method calculates the difference between now and the timestamp defined by constant YII_BEGIN_TIME. To estimate the execution time more accurately, the constant should be defined as early as possible (best at the beginning of the entry script.)

getLogs() method
public array getLogs(string $levels='', string $categories='')
$levels | string | level filter
$categories | string | category filter
{return} | array | list of messages. Each array elements represents one message with the following structure: array( [0] => message (string) [1] => level (string) [2] => category (string) [3] => timestamp (float, obtained by microtime(true));

Retrieves log messages.

Messages may be filtered by log levels and/or categories. A level filter is specified by a list of levels separated by comma or space (e.g. 'trace, error'). A category filter is similar to level filter (e.g. 'system, system.web'). A difference is that in category filter you can use pattern like 'system.*' to indicate all categories starting with 'system'.

If you do not specify level filter, it will bring back logs at all levels. The same applies to category filter.

Level filter and category filter are combinational, i.e., only messages satisfying both filter conditions will be returned.

getMemoryUsage() method
public integer getMemoryUsage()
{return} integer memory usage of the application (in bytes).

Returns the memory usage of the current application. This method relies on the PHP function memory_get_usage(). If it is not available, the method will attempt to use OS programs to determine the memory usage. A value 0 will be returned if the memory usage can still not be determined.

getProfilingResults() method (available since v1.0.6)
public array getProfilingResults(string $token=NULL, string $category=NULL, boolean $refresh=false)
$token | string | token filter. Defaults to null, meaning not filtered by token.
$category | string | category filter. Defaults to null, meaning not filtered by category.
$refresh | boolean | whether to refresh the internal timing calculations. If false, only the first time calling this method will the timings be calculated internally.
{return} | array | the profiling results.

Returns the profiling results. The results may be filtered by token and/or category. If no filter is specified, the returned results would be an array with each element being array($token,$category,$time). If a filter is specified, the results would be an array of timings.

log() method
public void log(string $message, string $level='info', string $category='application')
$message | string | message to be logged
$level | string | level of the message (e.g. 'Trace', 'Warning', 'Error'). It is case-insensitive.
$category | string | category of the message (e.g. 'system.web'). It is case-insensitive.

Logs a message. Messages logged by this method may be retrieved back via getLogs.

See Also

  • getLogs
onFlush() method (available since v1.1.0)
public void onFlush(CEvent $event)
$event CEvent the event parameter

Raises an onFlush event.


CProfileLogRoute

Package | system.logging
Inheritance | class CProfileLogRoute » CWebLogRoute » CLogRoute » CComponent
Since | 1.0
Version | $Id: CProfileLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CProfileLogRoute displays the profiling results in Web page.

The profiling is done by calling YiiBase::beginProfile() and YiiBase::endProfile(), which marks the begin and end of a code block.

CProfileLogRoute supports two types of report by setting the report property:
  • summary: list the execution time of every marked code block
  • callstack: list the mark code blocks in a hierarchical view reflecting their calling sequence.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
categories | string | list of categories separated by comma or space. | CLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
groupByToken | boolean | whether to aggregate results according to profiling tokens. | CProfileLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute
report | string | the type of the profiling report to display. | CProfileLogRoute
showInFireBug | boolean | whether the log should be displayed in FireBug instead of browser window. | CWebLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getReport() |  | CProfileLogRoute
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CProfileLogRoute
processLogs() | Displays the log messages. | CProfileLogRoute
raiseEvent() | Raises an event. | CComponent
setReport() |  | CProfileLogRoute

Protected Methods

Hide inherited methods

Method | Description | Defined By
aggregateResult() | Aggregates the report result. | CProfileLogRoute
displayCallstack() | Displays the callstack of the profiling procedures for display. | CProfileLogRoute
displaySummary() | Displays the summary report of the profiling result. | CProfileLogRoute
formatLogMessage() | Formats a log message given different fields. | CLogRoute
render() | Renders the view. | CWebLogRoute

Property Details

groupByToken property (available since v1.0.6)
public boolean $groupByToken;

whether to aggregate results according to profiling tokens. If false, the results will be aggregated by categories. Defaults to true. Note that this property only affects the summary report that is enabled when report is 'summary'.

report property
public string getReport()
public void setReport(string $value)

the type of the profiling report to display. Defaults to 'summary'.

Method Details

aggregateResult() method
protected void aggregateResult(array $result, float $delta)
$result | array | log result for this code block
$delta | float | time spent for this code block

Aggregates the report result.

displayCallstack() method
protected void displayCallstack(array $logs)
$logs array list of logs

Displays the callstack of the profiling procedures for display.

displaySummary() method
protected void displaySummary(array $logs)
$logs array list of logs

Displays the summary report of the profiling result.

getReport() method
public string getReport()
{return} string the type of the profiling report to display. Defaults to 'summary'.

init() method
public void init()

Initializes the route. This method is invoked after the route is created by the route manager.

processLogs() method
public void processLogs(array $logs)
$logs array list of log messages

Displays the log messages.

setReport() method
public void setReport(string $value)
$value string the type of the profiling report to display. Valid values include 'summary' and 'callstack'.


CWebLogRoute

Package | system.logging
Inheritance | class CWebLogRoute » CLogRoute » CComponent
Subclasses | CProfileLogRoute
Since | 1.0
Version | $Id: CWebLogRoute.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWebLogRoute shows the log content in Web page.

The log content can appear either at the end of the current Web page or in FireBug console window (if showInFireBug is set true).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
categories | string | list of categories separated by comma or space. | CLogRoute
enabled | boolean | whether to enable this log route. | CLogRoute
filter | mixed | the additional filter (e. | CLogRoute
levels | string | list of levels separated by comma or space. | CLogRoute
logs | array | the logs that are collected so far by this log route. | CLogRoute
showInFireBug | boolean | whether the log should be displayed in FireBug instead of browser window. | CWebLogRoute

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
collectLogs() | Retrieves filtered log messages from logger for further processing. | CLogRoute
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the route. | CLogRoute
processLogs() | Displays the log messages. | CWebLogRoute
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
formatLogMessage() | Formats a log message given different fields. | CLogRoute
render() | Renders the view. | CWebLogRoute

Property Details

showInFireBug property
public boolean $showInFireBug;

whether the log should be displayed in FireBug instead of browser window. Defaults to false.

Method Details

processLogs() method
public void processLogs(array $logs)
$logs array list of log messages

Displays the log messages.

render() method
protected void render(string $view, array $data)
$view | string | the view name (file name without extension). The file is assumed to be located under framework/data/views.
$data | array | data to be passed to the view

Renders the view.


CDbFixtureManager

Package | system.test
Inheritance | class CDbFixtureManager » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.1
Version | $Id: CDbFixtureManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbFixtureManager manages database fixtures during tests.

A fixture represents a list of rows for a specific table. For a test method, using a fixture means that at the begin of the method, the table has and only has the rows that are given in the fixture. Therefore, the table's state is predictable.

A fixture is represented as a PHP script whose name (without suffix) is the same as the table name (if schema name is needed, it should be prefixed to the table name). The PHP script returns an array representing a list of table rows. Each row is an associative array of column values indexed by column names.

A fixture can be associated with an init script which sits under the same fixture directory and is named as "TableName.init.php". The init script is used to initialize the table before populating the fixture data into the table. If the init script does not exist, the table will be emptied.

Fixtures must be stored under the basePath directory. The directory may contain a file named "init.php" which will be executed once to initialize the database. If this file is not found, all available fixtures will be loaded into the database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the base path containing all fixtures. | CDbFixtureManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
connectionID | string | the ID of the database connection. | CDbFixtureManager
dbConnection | CDbConnection | Returns the database connection used to load fixtures. | CDbFixtureManager
fixtures | array | Returns the names of the tables that have fixture data. | CDbFixtureManager
initScript | string | the name of the initialization script that would be executed before the whole test set runs. | CDbFixtureManager
initScriptSuffix | string | the suffix for fixture initialization scripts. | CDbFixtureManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
schemas | array | list of database schemas that the test tables may reside in. | CDbFixtureManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkIntegrity() | Enables or disables database integrity check. | CDbFixtureManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDbConnection() | Returns the database connection used to load fixtures. | CDbFixtureManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getFixtures() | Returns the names of the tables that have fixture data. | CDbFixtureManager
getIsInitialized() |  | CApplicationComponent
getRecord() | Returns the specified ActiveRecord instance in the fixture data. | CDbFixtureManager
getRows() | Returns the fixture data rows. | CDbFixtureManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this application component. | CDbFixtureManager
load() | Loads the specified fixtures. | CDbFixtureManager
loadFixture() | Loads the fixture for the specified table. | CDbFixtureManager
prepare() | Prepares the fixtures for the whole test. | CDbFixtureManager
raiseEvent() | Raises an event. | CComponent
resetTable() | Resets the table to the state that it contains no fixture data. | CDbFixtureManager
truncateTable() | Removes all rows from the specified table and resets its primary key sequence, if any. | CDbFixtureManager
truncateTables() | Truncates all tables in the specified schema. | CDbFixtureManager

Property Details

basePath property
public string $basePath;

the base path containing all fixtures. Defaults to null, meaning the path 'protected/tests/fixtures'.

connectionID property
public string $connectionID;

the ID of the database connection. Defaults to 'db'. Note, data in this database may be deleted or modified during testing. Make sure you have a backup database.

dbConnection property read-only
public CDbConnection getDbConnection()

Returns the database connection used to load fixtures.

fixtures property read-only
public array getFixtures()

Returns the names of the tables that have fixture data. All fixtures are assumed to be located under basePath.

initScript property
public string $initScript;

the name of the initialization script that would be executed before the whole test set runs. Defaults to 'init.php'. If the script does not exist, every table with a fixture file will be reset.

initScriptSuffix property
public string $initScriptSuffix;

the suffix for fixture initialization scripts. If a table is associated with such a script whose name is TableName suffixed this property value, then the script will be executed each time before the table is reset.

schemas property
public array $schemas;

list of database schemas that the test tables may reside in. Defaults to array(''), meaning using the default schema (an empty string refers to the default schema). This property is mainly used when turning on and off integrity checks so that fixture data can be populated into the database without causing problem.

Method Details

checkIntegrity() method
public void checkIntegrity(boolean $check)
$check boolean whether to enable database integrity check

Enables or disables database integrity check. This method may be used to temporarily turn off foreign constraints check.

getDbConnection() method
public CDbConnection getDbConnection()
{return} CDbConnection the database connection

Returns the database connection used to load fixtures.

getFixtures() method
public array getFixtures()
{return} array the names of the tables that have fixture data

Returns the names of the tables that have fixture data. All fixtures are assumed to be located under basePath.

getRecord() method
public CActiveRecord getRecord(string $name, string $alias)
$name | string | the fixture name
$alias | string | the alias for the fixture data row
{return} | CActiveRecord | the ActiveRecord instance. False is returned if there is no such fixture row.

Returns the specified ActiveRecord instance in the fixture data.

getRows() method
public array getRows(string $name)
$name | string | the fixture name
{return} | array | the fixture data rows. False is returned if there is no such fixture data.

Returns the fixture data rows. The rows will have updated primary key values if the primary key is auto-incremental.

init() method
public void init()

Initializes this application component.

load() method
public void load(array $fixtures)
$fixtures array fixtures to be loaded. The array keys are fixture names, and the array values are either AR class names or table names. If table names, they must begin with a colon character (e.g. 'Post' means an AR class, while ':Post' means a table name).

Loads the specified fixtures. For each fixture, the corresponding table will be reset first by calling resetTable and then be populated with the fixture data. The loaded fixture data may be later retrieved using getRows and getRecord. Note, if a table does not have fixture data, resetTable will still be called to reset the table.

loadFixture() method
public array loadFixture(string $tableName)
$tableName | string | table name
{return} | array | the loaded fixture rows indexed by row aliases (if any). False is returned if the table does not have a fixture.

Loads the fixture for the specified table. This method will insert rows given in the fixture into the corresponding table. The loaded rows will be returned by this method. If the table has auto-incremental primary key, each row will contain updated primary key value. If the fixture does not exist, this method will return false. Note, you may want to call resetTable before calling this method so that the table is emptied first.

prepare() method
public void prepare()

Prepares the fixtures for the whole test. This method is invoked in init. It executes the database init script if it exists. Otherwise, it will load all available fixtures.

resetTable() method
public void resetTable(string $tableName)
$tableName string the table name

Resets the table to the state that it contains no fixture data. If there is an init script named "tests/fixtures/TableName.init.php", the script will be executed. Otherwise, truncateTable will be invoked to delete all rows in the table and reset primary key sequence, if any.

truncateTable() method
public void truncateTable(string $tableName)
$tableName string the table name

Removes all rows from the specified table and resets its primary key sequence, if any. You may need to call checkIntegrity to turn off integrity check temporarily before you call this method.

truncateTables() method
public void truncateTables(string $schema='')
$schema string the schema name. Defaults to empty string, meaning the default database schema.

Truncates all tables in the specified schema. You may need to call checkIntegrity to turn off integrity check temporarily before you call this method.

See Also

  • truncateTable


CDbTestCase

Package | system.test
Inheritance | abstract class CDbTestCase » CTestCase » PHPUnit_Framework_TestCase » PHPUnit_Framework_Assert
Implements | PHPUnit_Framework_Test, Countable, PHPUnit_Framework_SelfDescribing
Since | 1.1
Version | $Id: CDbTestCase.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbTestCase is the base class for test cases about DB-related features.

CDbTestCase provides database fixture management with the help of CDbFixtureManager. By declaring fixtures property, one can ensure the specified tables have the expected fixture state when executing each test method. In addition, CDbTestCase provides two ways to access the fixture data.

For example, assume we declare fixtures to be:
public $fixtures=array(
    'posts' => 'Post',
    'comments' => 'Comment',
);

We can access the original fixture data rows using $this->posts $this->posts['first post']. We can also retrieve an ActiveRecord instance corresponding to a fixture data row using $this->posts('first post'). Note, here 'first post' refers to a key to a row in the original fixture data.

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
backupGlobals | boolean | Enable or disable the backup and restoration of the $GLOBALS array. | PHPUnit_Framework_TestCase
backupGlobalsBlacklist | array |  | PHPUnit_Framework_TestCase
backupStaticAttributes | boolean | Enable or disable the backup and restoration of static attributes. | PHPUnit_Framework_TestCase
backupStaticAttributesBlacklist | array |  | PHPUnit_Framework_TestCase
data | array |  | PHPUnit_Framework_TestCase
dataName | string |  | PHPUnit_Framework_TestCase
dependencies | array |  | PHPUnit_Framework_TestCase
dependencyInput | array |  | PHPUnit_Framework_TestCase
exceptionCode | integer |  | PHPUnit_Framework_TestCase
exceptionMessage | string |  | PHPUnit_Framework_TestCase
expectedException | mixed | The name of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionCode | integer | The code of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionMessage | string | The message of the expected Exception. | PHPUnit_Framework_TestCase
fixtures | array | a list of fixtures that should be loaded before each test method executes. | CDbTestCase
inIsolation | boolean | Whether or not this test is running in a separate PHP process. | PHPUnit_Framework_TestCase
iniSettings | Array |  | PHPUnit_Framework_TestCase
locale | Array |  | PHPUnit_Framework_TestCase
mockObjects | Array |  | PHPUnit_Framework_TestCase
name | string | The name of the test case. | PHPUnit_Framework_TestCase
numAssertions | integer |  | PHPUnit_Framework_TestCase
preserveGlobalState | boolean | Whether or not this test should preserve the global state when running in a separate PHP process. | PHPUnit_Framework_TestCase
result | PHPUnit_Framework_TestResult |  | PHPUnit_Framework_TestCase
runTestInSeparateProcess | boolean | Whether or not this test is to be run in a separate PHP process. | PHPUnit_Framework_TestCase
sharedFixture | mixed | Fixture that is shared between the tests of a test suite. | PHPUnit_Framework_TestCase
status | integer |  | PHPUnit_Framework_TestCase
statusMessage | string |  | PHPUnit_Framework_TestCase
testResult | mixed |  | PHPUnit_Framework_TestCase
useErrorHandler | boolean |  | PHPUnit_Framework_TestCase
useOutputBuffering | boolean |  | PHPUnit_Framework_TestCase

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | PHP magic method. | CDbTestCase
__construct() | Constructs a test case with the given name. | PHPUnit_Framework_TestCase
__get() | PHP magic method. | CDbTestCase
addToAssertionCount() | Adds a value to the assertion counter. | PHPUnit_Framework_TestCase
anything() | Returns a PHPUnit_Framework_Constraint_IsAnything matcher object. | PHPUnit_Framework_Assert
arrayHasKey() | Returns a PHPUnit_Framework_Constraint_ArrayHasKey matcher object. | PHPUnit_Framework_Assert
assertArrayHasKey() | Asserts that an array has a specified key. | PHPUnit_Framework_Assert
assertArrayNotHasKey() | Asserts that an array does not have a specified key. | PHPUnit_Framework_Assert
assertAttributeContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeEquals() | Asserts that a variable is equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeGreaterThan() | Asserts that an attribute is greater than another value. | PHPUnit_Framework_Assert
assertAttributeGreaterThanOrEqual() | Asserts that an attribute is greater than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeLessThan() | Asserts that an attribute is smaller than another value. | PHPUnit_Framework_Assert
assertAttributeLessThanOrEqual() | Asserts that an attribute is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeNotContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotEquals() | Asserts that a variable is not equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeNotSame() | Asserts that a variable and an attribute of an object do not have the | PHPUnit_Framework_Assert
assertAttributeNotType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertAttributeSame() | Asserts that a variable and an attribute of an object have the same type | PHPUnit_Framework_Assert
assertAttributeType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertClassHasAttribute() | Asserts that a class has a specified attribute. | PHPUnit_Framework_Assert
assertClassHasStaticAttribute() | Asserts that a class has a specified static attribute. | PHPUnit_Framework_Assert
assertClassNotHasAttribute() | Asserts that a class does not have a specified attribute. | PHPUnit_Framework_Assert
assertClassNotHasStaticAttribute() | Asserts that a class does not have a specified static attribute. | PHPUnit_Framework_Assert
assertContains() | Asserts that a haystack contains a needle. | PHPUnit_Framework_Assert
assertContainsOnly() | Asserts that a haystack contains only values of a given type. | PHPUnit_Framework_Assert
assertEqualXMLStructure() | Asserts that a hierarchy of DOMNodes matches. | PHPUnit_Framework_Assert
assertEquals() | Asserts that two variables are equal. | PHPUnit_Framework_Assert
assertFalse() | Asserts that a condition is false. | PHPUnit_Framework_Assert
assertFileEquals() | Asserts that the contents of one file is equal to the contents of another | PHPUnit_Framework_Assert
assertFileExists() | Asserts that a file exists. | PHPUnit_Framework_Assert
assertFileNotEquals() | Asserts that the contents of one file is not equal to the contents of | PHPUnit_Framework_Assert
assertFileNotExists() | Asserts that a file does not exist. | PHPUnit_Framework_Assert
assertGreaterThan() | Asserts that a value is greater than another value. | PHPUnit_Framework_Assert
assertGreaterThanOrEqual() | Asserts that a value is greater than or equal to another value. | PHPUnit_Framework_Assert
assertLessThan() | Asserts that a value is smaller than another value. | PHPUnit_Framework_Assert
assertLessThanOrEqual() | Asserts that a value is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertNotContains() | Asserts that a haystack does not contain a needle. | PHPUnit_Framework_Assert
assertNotContainsOnly() | Asserts that a haystack does not contain only values of a given type. | PHPUnit_Framework_Assert
assertNotEquals() | Asserts that two variables are not equal. | PHPUnit_Framework_Assert
assertNotNull() | Asserts that a variable is not NULL. | PHPUnit_Framework_Assert
assertNotRegExp() | Asserts that a string does not match a given regular expression. | PHPUnit_Framework_Assert
assertNotSame() | Asserts that two variables do not have the same type and value. | PHPUnit_Framework_Assert
assertNotTag() | This assertion is the exact opposite of assertTag(). | PHPUnit_Framework_Assert
assertNotType() | Asserts that a variable is not of a given type. | PHPUnit_Framework_Assert
assertNull() | Asserts that a variable is NULL. | PHPUnit_Framework_Assert
assertObjectHasAttribute() | Asserts that an object has a specified attribute. | PHPUnit_Framework_Assert
assertObjectNotHasAttribute() | Asserts that an object does not have a specified attribute. | PHPUnit_Framework_Assert
assertRegExp() | Asserts that a string matches a given regular expression. | PHPUnit_Framework_Assert
assertSame() | Asserts that two variables have the same type and value. | PHPUnit_Framework_Assert
assertSelectCount() | Assert the presence, absence, or count of elements in a document matching | PHPUnit_Framework_Assert
assertSelectEquals() | assertSelectEquals("#binder .name", "Chuck", true, $xml); // any? | PHPUnit_Framework_Assert
assertSelectRegExp() | assertSelectRegExp("#binder .name", "/Mike|Derek/", true, $xml); // any? | PHPUnit_Framework_Assert
assertStringEndsNotWith() | Asserts that a string ends not with a given prefix. | PHPUnit_Framework_Assert
assertStringEndsWith() | Asserts that a string ends with a given prefix. | PHPUnit_Framework_Assert
assertStringEqualsFile() | Asserts that the contents of a string is equal | PHPUnit_Framework_Assert
assertStringNotEqualsFile() | Asserts that the contents of a string is not equal | PHPUnit_Framework_Assert
assertStringStartsNotWith() | Asserts that a string starts not with a given prefix. | PHPUnit_Framework_Assert
assertStringStartsWith() | Asserts that a string starts with a given prefix. | PHPUnit_Framework_Assert
assertTag() | Evaluate an HTML or XML string and assert its structure and/or contents. | PHPUnit_Framework_Assert
assertThat() | Evaluates a PHPUnit_Framework_Constraint matcher object. | PHPUnit_Framework_Assert
assertTrue() | Asserts that a condition is true. | PHPUnit_Framework_Assert
assertType() | Asserts that a variable is of a given type. | PHPUnit_Framework_Assert
assertXmlFileEqualsXmlFile() | Asserts that two XML files are equal. | PHPUnit_Framework_Assert
assertXmlFileNotEqualsXmlFile() | Asserts that two XML files are not equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlFile() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlString() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlFile() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlString() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
attribute() | Returns a PHPUnit_Framework_Constraint_Attribute matcher object. | PHPUnit_Framework_Assert
attributeEqualTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object | PHPUnit_Framework_Assert
classHasAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasAttribute matcher object. | PHPUnit_Framework_Assert
classHasStaticAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasStaticAttribute matcher | PHPUnit_Framework_Assert
contains() | Returns a PHPUnit_Framework_Constraint_TraversableContains matcher | PHPUnit_Framework_Assert
containsOnly() | Returns a PHPUnit_Framework_Constraint_TraversableContainsOnly matcher | PHPUnit_Framework_Assert
count() | Counts the number of test cases executed by run(TestResult result). | PHPUnit_Framework_TestCase
equalTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object. | PHPUnit_Framework_Assert
fail() | Fails a test with the given message. | PHPUnit_Framework_Assert
fileExists() | Returns a PHPUnit_Framework_Constraint_FileExists matcher object. | PHPUnit_Framework_Assert
getAnnotations() | Returns the annotations for this test. | PHPUnit_Framework_TestCase
getCount() | Return the current assertion count. | PHPUnit_Framework_Assert
getExpectedException() |  | PHPUnit_Framework_TestCase
getFixtureData() |  | CDbTestCase
getFixtureManager() |  | CDbTestCase
getFixtureRecord() |  | CDbTestCase
getName() | Gets the name of a TestCase. | PHPUnit_Framework_TestCase
getNumAssertions() | Returns the number of assertions performed by this test. | PHPUnit_Framework_TestCase
getResult() |  | PHPUnit_Framework_TestCase
getStatus() | Returns the status of this test. | PHPUnit_Framework_TestCase
getStatusMessage() | Returns the status message of this test. | PHPUnit_Framework_TestCase
greaterThan() | Returns a PHPUnit_Framework_Constraint_GreaterThan matcher object. | PHPUnit_Framework_Assert
greaterThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
hasFailed() | Returns whether or not this test has failed. | PHPUnit_Framework_TestCase
identicalTo() | Returns a PHPUnit_Framework_Constraint_IsIdentical matcher object. | PHPUnit_Framework_Assert
isFalse() | Returns a PHPUnit_Framework_Constraint_IsFalse matcher object. | PHPUnit_Framework_Assert
isInstanceOf() | Returns a PHPUnit_Framework_Constraint_IsInstanceOf matcher object. | PHPUnit_Framework_Assert
isNull() | Returns a PHPUnit_Framework_Constraint_IsNull matcher object. | PHPUnit_Framework_Assert
isTrue() | Returns a PHPUnit_Framework_Constraint_IsTrue matcher object. | PHPUnit_Framework_Assert
isType() | Returns a PHPUnit_Framework_Constraint_IsType matcher object. | PHPUnit_Framework_Assert
lessThan() | Returns a PHPUnit_Framework_Constraint_LessThan matcher object. | PHPUnit_Framework_Assert
lessThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
logicalAnd() | Returns a PHPUnit_Framework_Constraint_And matcher object. | PHPUnit_Framework_Assert
logicalNot() | Returns a PHPUnit_Framework_Constraint_Not matcher object. | PHPUnit_Framework_Assert
logicalOr() | Returns a PHPUnit_Framework_Constraint_Or matcher object. | PHPUnit_Framework_Assert
logicalXor() | Returns a PHPUnit_Framework_Constraint_Xor matcher object. | PHPUnit_Framework_Assert
markTestIncomplete() | Mark the test as incomplete. | PHPUnit_Framework_Assert
markTestSkipped() | Mark the test as skipped. | PHPUnit_Framework_Assert
matchesRegularExpression() | Returns a PHPUnit_Framework_Constraint_PCREMatch matcher object. | PHPUnit_Framework_Assert
objectHasAttribute() | Returns a PHPUnit_Framework_Constraint_ObjectHasAttribute matcher object. | PHPUnit_Framework_Assert
readAttribute() | Returns the value of an attribute of a class or an object. | PHPUnit_Framework_Assert
resetCount() | Reset the assertion counter. | PHPUnit_Framework_Assert
run() | Runs the test case and collects the results in a TestResult object. | PHPUnit_Framework_TestCase
runBare() | Runs the bare test sequence. | PHPUnit_Framework_TestCase
setBackupGlobals() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setBackupStaticAttributes() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setDependencies() | Sets the dependencies of a TestCase. | PHPUnit_Framework_TestCase
setDependencyInput() | Sets | PHPUnit_Framework_TestCase
setExpectedException() |  | PHPUnit_Framework_TestCase
setInIsolation() |  | PHPUnit_Framework_TestCase
setName() | Sets the name of a TestCase. | PHPUnit_Framework_TestCase
setPreserveGlobalState() |  | PHPUnit_Framework_TestCase
setResult() |  | PHPUnit_Framework_TestCase
setRunTestInSeparateProcess() |  | PHPUnit_Framework_TestCase
setSharedFixture() | Sets the shared fixture. | PHPUnit_Framework_TestCase
setUpBeforeClass() | This method is called before the first test of this test class is run. | PHPUnit_Framework_TestCase
setUseErrorHandler() |  | PHPUnit_Framework_TestCase
setUseOutputBuffering() |  | PHPUnit_Framework_TestCase
stringContains() | Returns a PHPUnit_Framework_Constraint_StringContains matcher object. | PHPUnit_Framework_Assert
stringEndsWith() | Returns a PHPUnit_Framework_Constraint_StringEndsWith matcher object. | PHPUnit_Framework_Assert
stringStartsWith() | Returns a PHPUnit_Framework_Constraint_StringStartsWith matcher object. | PHPUnit_Framework_Assert
tearDownAfterClass() | This method is called after the last test of this test class is run. | PHPUnit_Framework_TestCase
toString() | Returns a string representation of the test case. | PHPUnit_Framework_TestCase

Protected Methods

Hide inherited methods

Method | Description | Defined By
any() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
assertPostConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
assertPreConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
at() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
atLeastOnce() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
createResult() | Creates a default TestResult object. | PHPUnit_Framework_TestCase
dataToString() |  | PHPUnit_Framework_TestCase
exactly() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
getDataSetAsString() | Gets the data set description of a TestCase. | PHPUnit_Framework_TestCase
getMock() | Returns a mock object for the specified class. | PHPUnit_Framework_TestCase
getMockForAbstractClass() | Returns a mock object for the specified abstract class with all abstract | PHPUnit_Framework_TestCase
getMockFromWsdl() | Returns a mock object based on the given WSDL file. | PHPUnit_Framework_TestCase
iniSet() | This method is a wrapper for the ini_set() function that automatically | PHPUnit_Framework_TestCase
never() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
onConsecutiveCalls() |  | PHPUnit_Framework_TestCase
onNotSuccessfulTest() | This method is called when a test method did not execute successfully. | PHPUnit_Framework_TestCase
once() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
prepareTemplate() | Performs custom preparations on the process isolation template. | PHPUnit_Framework_TestCase
returnArgument() |  | PHPUnit_Framework_TestCase
returnCallback() |  | PHPUnit_Framework_TestCase
returnValue() |  | PHPUnit_Framework_TestCase
runTest() | Override to run the test and assert its state. | PHPUnit_Framework_TestCase
setExpectedExceptionFromAnnotation() |  | PHPUnit_Framework_TestCase
setLocale() | This method is a wrapper for the setlocale() function that automatically | PHPUnit_Framework_TestCase
setUp() | Sets up the fixture before executing a test method. | CDbTestCase
setUseErrorHandlerFromAnnotation() |  | PHPUnit_Framework_TestCase
setUseOutputBufferingFromAnnotation() |  | PHPUnit_Framework_TestCase
tearDown() | Tears down the fixture, for example, close a network connection. | PHPUnit_Framework_TestCase
throwException() |  | PHPUnit_Framework_TestCase

Property Details

fixtures property
protected array $fixtures;

a list of fixtures that should be loaded before each test method executes. The array keys are fixture names, and the array values are either AR class names or table names. If table names, they must begin with a colon character (e.g. 'Post' means an AR class, while ':Post' means a table name). Defaults to false, meaning fixtures will not be used at all.

Method Details

__call() method
public mixed __call(string $name, string $params)
$name | string | method name
$params | string | method parameters
{return} | mixed | the property value

PHP magic method. This method is overridden so that named fixture ActiveRecord instances can be accessed in terms of a method call.

__get() method
public mixed __get(string $name)
$name | string | the property name
{return} | mixed | the property value

PHP magic method. This method is overridden so that named fixture data can be accessed like a normal property.

getFixtureData() method
public array getFixtureData(string $name)
$name | string | the fixture name (the key value in fixtures).
{return} | array | the named fixture data

getFixtureManager() method
public CDbFixtureManager getFixtureManager()
{return} CDbFixtureManager the database fixture manager

getFixtureRecord() method
public CActiveRecord getFixtureRecord(string $name, string $alias)
$name | string | the fixture name (the key value in fixtures).
$alias | string | the alias of the fixture data row
{return} | CActiveRecord | the ActiveRecord instance corresponding to the specified alias in the named fixture. False is returned if there is no such fixture or the record cannot be found.

setUp() method
protected void setUp()

Sets up the fixture before executing a test method. If you override this method, make sure the parent implementation is invoked. Otherwise, the database fixtures will not be managed properly.


CTestCase

Package | system.test
Inheritance | abstract class CTestCase » PHPUnit_Framework_TestCase » PHPUnit_Framework_Assert
Implements | PHPUnit_Framework_SelfDescribing, Countable, PHPUnit_Framework_Test
Subclasses | CDbTestCase
Since | 1.1
Version | $Id: CTestCase.php 1907 2010-03-14 05:14:49Z qiang.xue $
CTestCase is the base class for all test case classes.

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
backupGlobals | boolean | Enable or disable the backup and restoration of the $GLOBALS array. | PHPUnit_Framework_TestCase
backupGlobalsBlacklist | array |  | PHPUnit_Framework_TestCase
backupStaticAttributes | boolean | Enable or disable the backup and restoration of static attributes. | PHPUnit_Framework_TestCase
backupStaticAttributesBlacklist | array |  | PHPUnit_Framework_TestCase
data | array |  | PHPUnit_Framework_TestCase
dataName | string |  | PHPUnit_Framework_TestCase
dependencies | array |  | PHPUnit_Framework_TestCase
dependencyInput | array |  | PHPUnit_Framework_TestCase
exceptionCode | integer |  | PHPUnit_Framework_TestCase
exceptionMessage | string |  | PHPUnit_Framework_TestCase
expectedException | mixed | The name of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionCode | integer | The code of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionMessage | string | The message of the expected Exception. | PHPUnit_Framework_TestCase
inIsolation | boolean | Whether or not this test is running in a separate PHP process. | PHPUnit_Framework_TestCase
iniSettings | Array |  | PHPUnit_Framework_TestCase
locale | Array |  | PHPUnit_Framework_TestCase
mockObjects | Array |  | PHPUnit_Framework_TestCase
name | string | The name of the test case. | PHPUnit_Framework_TestCase
numAssertions | integer |  | PHPUnit_Framework_TestCase
preserveGlobalState | boolean | Whether or not this test should preserve the global state when running in a separate PHP process. | PHPUnit_Framework_TestCase
result | PHPUnit_Framework_TestResult |  | PHPUnit_Framework_TestCase
runTestInSeparateProcess | boolean | Whether or not this test is to be run in a separate PHP process. | PHPUnit_Framework_TestCase
sharedFixture | mixed | Fixture that is shared between the tests of a test suite. | PHPUnit_Framework_TestCase
status | integer |  | PHPUnit_Framework_TestCase
statusMessage | string |  | PHPUnit_Framework_TestCase
testResult | mixed |  | PHPUnit_Framework_TestCase
useErrorHandler | boolean |  | PHPUnit_Framework_TestCase
useOutputBuffering | boolean |  | PHPUnit_Framework_TestCase

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructs a test case with the given name. | PHPUnit_Framework_TestCase
addToAssertionCount() | Adds a value to the assertion counter. | PHPUnit_Framework_TestCase
anything() | Returns a PHPUnit_Framework_Constraint_IsAnything matcher object. | PHPUnit_Framework_Assert
arrayHasKey() | Returns a PHPUnit_Framework_Constraint_ArrayHasKey matcher object. | PHPUnit_Framework_Assert
assertArrayHasKey() | Asserts that an array has a specified key. | PHPUnit_Framework_Assert
assertArrayNotHasKey() | Asserts that an array does not have a specified key. | PHPUnit_Framework_Assert
assertAttributeContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeEquals() | Asserts that a variable is equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeGreaterThan() | Asserts that an attribute is greater than another value. | PHPUnit_Framework_Assert
assertAttributeGreaterThanOrEqual() | Asserts that an attribute is greater than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeLessThan() | Asserts that an attribute is smaller than another value. | PHPUnit_Framework_Assert
assertAttributeLessThanOrEqual() | Asserts that an attribute is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeNotContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotEquals() | Asserts that a variable is not equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeNotSame() | Asserts that a variable and an attribute of an object do not have the | PHPUnit_Framework_Assert
assertAttributeNotType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertAttributeSame() | Asserts that a variable and an attribute of an object have the same type | PHPUnit_Framework_Assert
assertAttributeType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertClassHasAttribute() | Asserts that a class has a specified attribute. | PHPUnit_Framework_Assert
assertClassHasStaticAttribute() | Asserts that a class has a specified static attribute. | PHPUnit_Framework_Assert
assertClassNotHasAttribute() | Asserts that a class does not have a specified attribute. | PHPUnit_Framework_Assert
assertClassNotHasStaticAttribute() | Asserts that a class does not have a specified static attribute. | PHPUnit_Framework_Assert
assertContains() | Asserts that a haystack contains a needle. | PHPUnit_Framework_Assert
assertContainsOnly() | Asserts that a haystack contains only values of a given type. | PHPUnit_Framework_Assert
assertEqualXMLStructure() | Asserts that a hierarchy of DOMNodes matches. | PHPUnit_Framework_Assert
assertEquals() | Asserts that two variables are equal. | PHPUnit_Framework_Assert
assertFalse() | Asserts that a condition is false. | PHPUnit_Framework_Assert
assertFileEquals() | Asserts that the contents of one file is equal to the contents of another | PHPUnit_Framework_Assert
assertFileExists() | Asserts that a file exists. | PHPUnit_Framework_Assert
assertFileNotEquals() | Asserts that the contents of one file is not equal to the contents of | PHPUnit_Framework_Assert
assertFileNotExists() | Asserts that a file does not exist. | PHPUnit_Framework_Assert
assertGreaterThan() | Asserts that a value is greater than another value. | PHPUnit_Framework_Assert
assertGreaterThanOrEqual() | Asserts that a value is greater than or equal to another value. | PHPUnit_Framework_Assert
assertLessThan() | Asserts that a value is smaller than another value. | PHPUnit_Framework_Assert
assertLessThanOrEqual() | Asserts that a value is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertNotContains() | Asserts that a haystack does not contain a needle. | PHPUnit_Framework_Assert
assertNotContainsOnly() | Asserts that a haystack does not contain only values of a given type. | PHPUnit_Framework_Assert
assertNotEquals() | Asserts that two variables are not equal. | PHPUnit_Framework_Assert
assertNotNull() | Asserts that a variable is not NULL. | PHPUnit_Framework_Assert
assertNotRegExp() | Asserts that a string does not match a given regular expression. | PHPUnit_Framework_Assert
assertNotSame() | Asserts that two variables do not have the same type and value. | PHPUnit_Framework_Assert
assertNotTag() | This assertion is the exact opposite of assertTag(). | PHPUnit_Framework_Assert
assertNotType() | Asserts that a variable is not of a given type. | PHPUnit_Framework_Assert
assertNull() | Asserts that a variable is NULL. | PHPUnit_Framework_Assert
assertObjectHasAttribute() | Asserts that an object has a specified attribute. | PHPUnit_Framework_Assert
assertObjectNotHasAttribute() | Asserts that an object does not have a specified attribute. | PHPUnit_Framework_Assert
assertRegExp() | Asserts that a string matches a given regular expression. | PHPUnit_Framework_Assert
assertSame() | Asserts that two variables have the same type and value. | PHPUnit_Framework_Assert
assertSelectCount() | Assert the presence, absence, or count of elements in a document matching | PHPUnit_Framework_Assert
assertSelectEquals() | assertSelectEquals("#binder .name", "Chuck", true, $xml); // any? | PHPUnit_Framework_Assert
assertSelectRegExp() | assertSelectRegExp("#binder .name", "/Mike|Derek/", true, $xml); // any? | PHPUnit_Framework_Assert
assertStringEndsNotWith() | Asserts that a string ends not with a given prefix. | PHPUnit_Framework_Assert
assertStringEndsWith() | Asserts that a string ends with a given prefix. | PHPUnit_Framework_Assert
assertStringEqualsFile() | Asserts that the contents of a string is equal | PHPUnit_Framework_Assert
assertStringNotEqualsFile() | Asserts that the contents of a string is not equal | PHPUnit_Framework_Assert
assertStringStartsNotWith() | Asserts that a string starts not with a given prefix. | PHPUnit_Framework_Assert
assertStringStartsWith() | Asserts that a string starts with a given prefix. | PHPUnit_Framework_Assert
assertTag() | Evaluate an HTML or XML string and assert its structure and/or contents. | PHPUnit_Framework_Assert
assertThat() | Evaluates a PHPUnit_Framework_Constraint matcher object. | PHPUnit_Framework_Assert
assertTrue() | Asserts that a condition is true. | PHPUnit_Framework_Assert
assertType() | Asserts that a variable is of a given type. | PHPUnit_Framework_Assert
assertXmlFileEqualsXmlFile() | Asserts that two XML files are equal. | PHPUnit_Framework_Assert
assertXmlFileNotEqualsXmlFile() | Asserts that two XML files are not equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlFile() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlString() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlFile() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlString() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
attribute() | Returns a PHPUnit_Framework_Constraint_Attribute matcher object. | PHPUnit_Framework_Assert
attributeEqualTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object | PHPUnit_Framework_Assert
classHasAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasAttribute matcher object. | PHPUnit_Framework_Assert
classHasStaticAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasStaticAttribute matcher | PHPUnit_Framework_Assert
contains() | Returns a PHPUnit_Framework_Constraint_TraversableContains matcher | PHPUnit_Framework_Assert
containsOnly() | Returns a PHPUnit_Framework_Constraint_TraversableContainsOnly matcher | PHPUnit_Framework_Assert
count() | Counts the number of test cases executed by run(TestResult result). | PHPUnit_Framework_TestCase
equalTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object. | PHPUnit_Framework_Assert
fail() | Fails a test with the given message. | PHPUnit_Framework_Assert
fileExists() | Returns a PHPUnit_Framework_Constraint_FileExists matcher object. | PHPUnit_Framework_Assert
getAnnotations() | Returns the annotations for this test. | PHPUnit_Framework_TestCase
getCount() | Return the current assertion count. | PHPUnit_Framework_Assert
getExpectedException() |  | PHPUnit_Framework_TestCase
getName() | Gets the name of a TestCase. | PHPUnit_Framework_TestCase
getNumAssertions() | Returns the number of assertions performed by this test. | PHPUnit_Framework_TestCase
getResult() |  | PHPUnit_Framework_TestCase
getStatus() | Returns the status of this test. | PHPUnit_Framework_TestCase
getStatusMessage() | Returns the status message of this test. | PHPUnit_Framework_TestCase
greaterThan() | Returns a PHPUnit_Framework_Constraint_GreaterThan matcher object. | PHPUnit_Framework_Assert
greaterThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
hasFailed() | Returns whether or not this test has failed. | PHPUnit_Framework_TestCase
identicalTo() | Returns a PHPUnit_Framework_Constraint_IsIdentical matcher object. | PHPUnit_Framework_Assert
isFalse() | Returns a PHPUnit_Framework_Constraint_IsFalse matcher object. | PHPUnit_Framework_Assert
isInstanceOf() | Returns a PHPUnit_Framework_Constraint_IsInstanceOf matcher object. | PHPUnit_Framework_Assert
isNull() | Returns a PHPUnit_Framework_Constraint_IsNull matcher object. | PHPUnit_Framework_Assert
isTrue() | Returns a PHPUnit_Framework_Constraint_IsTrue matcher object. | PHPUnit_Framework_Assert
isType() | Returns a PHPUnit_Framework_Constraint_IsType matcher object. | PHPUnit_Framework_Assert
lessThan() | Returns a PHPUnit_Framework_Constraint_LessThan matcher object. | PHPUnit_Framework_Assert
lessThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
logicalAnd() | Returns a PHPUnit_Framework_Constraint_And matcher object. | PHPUnit_Framework_Assert
logicalNot() | Returns a PHPUnit_Framework_Constraint_Not matcher object. | PHPUnit_Framework_Assert
logicalOr() | Returns a PHPUnit_Framework_Constraint_Or matcher object. | PHPUnit_Framework_Assert
logicalXor() | Returns a PHPUnit_Framework_Constraint_Xor matcher object. | PHPUnit_Framework_Assert
markTestIncomplete() | Mark the test as incomplete. | PHPUnit_Framework_Assert
markTestSkipped() | Mark the test as skipped. | PHPUnit_Framework_Assert
matchesRegularExpression() | Returns a PHPUnit_Framework_Constraint_PCREMatch matcher object. | PHPUnit_Framework_Assert
objectHasAttribute() | Returns a PHPUnit_Framework_Constraint_ObjectHasAttribute matcher object. | PHPUnit_Framework_Assert
readAttribute() | Returns the value of an attribute of a class or an object. | PHPUnit_Framework_Assert
resetCount() | Reset the assertion counter. | PHPUnit_Framework_Assert
run() | Runs the test case and collects the results in a TestResult object. | PHPUnit_Framework_TestCase
runBare() | Runs the bare test sequence. | PHPUnit_Framework_TestCase
setBackupGlobals() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setBackupStaticAttributes() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setDependencies() | Sets the dependencies of a TestCase. | PHPUnit_Framework_TestCase
setDependencyInput() | Sets | PHPUnit_Framework_TestCase
setExpectedException() |  | PHPUnit_Framework_TestCase
setInIsolation() |  | PHPUnit_Framework_TestCase
setName() | Sets the name of a TestCase. | PHPUnit_Framework_TestCase
setPreserveGlobalState() |  | PHPUnit_Framework_TestCase
setResult() |  | PHPUnit_Framework_TestCase
setRunTestInSeparateProcess() |  | PHPUnit_Framework_TestCase
setSharedFixture() | Sets the shared fixture. | PHPUnit_Framework_TestCase
setUpBeforeClass() | This method is called before the first test of this test class is run. | PHPUnit_Framework_TestCase
setUseErrorHandler() |  | PHPUnit_Framework_TestCase
setUseOutputBuffering() |  | PHPUnit_Framework_TestCase
stringContains() | Returns a PHPUnit_Framework_Constraint_StringContains matcher object. | PHPUnit_Framework_Assert
stringEndsWith() | Returns a PHPUnit_Framework_Constraint_StringEndsWith matcher object. | PHPUnit_Framework_Assert
stringStartsWith() | Returns a PHPUnit_Framework_Constraint_StringStartsWith matcher object. | PHPUnit_Framework_Assert
tearDownAfterClass() | This method is called after the last test of this test class is run. | PHPUnit_Framework_TestCase
toString() | Returns a string representation of the test case. | PHPUnit_Framework_TestCase

Protected Methods

Hide inherited methods

Method | Description | Defined By
any() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
assertPostConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
assertPreConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
at() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
atLeastOnce() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
createResult() | Creates a default TestResult object. | PHPUnit_Framework_TestCase
dataToString() |  | PHPUnit_Framework_TestCase
exactly() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
getDataSetAsString() | Gets the data set description of a TestCase. | PHPUnit_Framework_TestCase
getMock() | Returns a mock object for the specified class. | PHPUnit_Framework_TestCase
getMockForAbstractClass() | Returns a mock object for the specified abstract class with all abstract | PHPUnit_Framework_TestCase
getMockFromWsdl() | Returns a mock object based on the given WSDL file. | PHPUnit_Framework_TestCase
iniSet() | This method is a wrapper for the ini_set() function that automatically | PHPUnit_Framework_TestCase
never() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
onConsecutiveCalls() |  | PHPUnit_Framework_TestCase
onNotSuccessfulTest() | This method is called when a test method did not execute successfully. | PHPUnit_Framework_TestCase
once() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
prepareTemplate() | Performs custom preparations on the process isolation template. | PHPUnit_Framework_TestCase
returnArgument() |  | PHPUnit_Framework_TestCase
returnCallback() |  | PHPUnit_Framework_TestCase
returnValue() |  | PHPUnit_Framework_TestCase
runTest() | Override to run the test and assert its state. | PHPUnit_Framework_TestCase
setExpectedExceptionFromAnnotation() |  | PHPUnit_Framework_TestCase
setLocale() | This method is a wrapper for the setlocale() function that automatically | PHPUnit_Framework_TestCase
setUp() | Sets up the fixture, for example, open a network connection. | PHPUnit_Framework_TestCase
setUseErrorHandlerFromAnnotation() |  | PHPUnit_Framework_TestCase
setUseOutputBufferingFromAnnotation() |  | PHPUnit_Framework_TestCase
tearDown() | Tears down the fixture, for example, close a network connection. | PHPUnit_Framework_TestCase
throwException() |  | PHPUnit_Framework_TestCase


CWebTestCase

Package | system.test
Inheritance | abstract class CWebTestCase » PHPUnit_Extensions_SeleniumTestCase » PHPUnit_Framework_TestCase » PHPUnit_Framework_Assert
Implements | PHPUnit_Framework_Test, Countable, PHPUnit_Framework_SelfDescribing
Since | 1.1
Version | $Id: CWebTestCase.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWebTestCase is the base class for Web-based functional test case classes.

It extends PHPUnit_Extensions_SeleniumTestCase and provides the database fixture management feature like CDbTestCase.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
browsers | array |  | PHPUnit_Extensions_SeleniumTestCase

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
autoStop | boolean |  | PHPUnit_Extensions_SeleniumTestCase
backupGlobals | boolean | Enable or disable the backup and restoration of the $GLOBALS array. | PHPUnit_Framework_TestCase
backupGlobalsBlacklist | array |  | PHPUnit_Framework_TestCase
backupStaticAttributes | boolean | Enable or disable the backup and restoration of static attributes. | PHPUnit_Framework_TestCase
backupStaticAttributesBlacklist | array |  | PHPUnit_Framework_TestCase
browserName | string |  | PHPUnit_Extensions_SeleniumTestCase
captureScreenshotOnFailure | boolean |  | PHPUnit_Extensions_SeleniumTestCase
collectCodeCoverageInformation | boolean |  | PHPUnit_Extensions_SeleniumTestCase
coverageScriptUrl | string |  | PHPUnit_Extensions_SeleniumTestCase
data | array |  | PHPUnit_Framework_TestCase
dataName | string |  | PHPUnit_Framework_TestCase
dependencies | array |  | PHPUnit_Framework_TestCase
dependencyInput | array |  | PHPUnit_Framework_TestCase
drivers | PHPUnit_Extensions_SeleniumTestCase_Driver[] |  | PHPUnit_Extensions_SeleniumTestCase
exceptionCode | integer |  | PHPUnit_Framework_TestCase
exceptionMessage | string |  | PHPUnit_Framework_TestCase
expectedException | mixed | The name of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionCode | integer | The code of the expected Exception. | PHPUnit_Framework_TestCase
expectedExceptionMessage | string | The message of the expected Exception. | PHPUnit_Framework_TestCase
fixtures | array | a list of fixtures that should be loaded before each test method executes. | CWebTestCase
inDefaultAssertions | boolean |  | PHPUnit_Extensions_SeleniumTestCase
inIsolation | boolean | Whether or not this test is running in a separate PHP process. | PHPUnit_Framework_TestCase
iniSettings | Array |  | PHPUnit_Framework_TestCase
locale | Array |  | PHPUnit_Framework_TestCase
mockObjects | Array |  | PHPUnit_Framework_TestCase
name | string | The name of the test case. | PHPUnit_Framework_TestCase
numAssertions | integer |  | PHPUnit_Framework_TestCase
preserveGlobalState | boolean | Whether or not this test should preserve the global state when running in a separate PHP process. | PHPUnit_Framework_TestCase
result | PHPUnit_Framework_TestResult |  | PHPUnit_Framework_TestCase
runTestInSeparateProcess | boolean | Whether or not this test is to be run in a separate PHP process. | PHPUnit_Framework_TestCase
screenshotPath | string |  | PHPUnit_Extensions_SeleniumTestCase
screenshotUrl | string |  | PHPUnit_Extensions_SeleniumTestCase
sharedFixture | mixed | Fixture that is shared between the tests of a test suite. | PHPUnit_Framework_TestCase
status | integer |  | PHPUnit_Framework_TestCase
statusMessage | string |  | PHPUnit_Framework_TestCase
testId | string |  | PHPUnit_Extensions_SeleniumTestCase
testResult | mixed |  | PHPUnit_Framework_TestCase
useErrorHandler | boolean |  | PHPUnit_Framework_TestCase
useOutputBuffering | boolean |  | PHPUnit_Framework_TestCase
verificationErrors | array |  | PHPUnit_Extensions_SeleniumTestCase

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | PHP magic method. | CWebTestCase
__construct() |  | PHPUnit_Extensions_SeleniumTestCase
__get() | PHP magic method. | CWebTestCase
addToAssertionCount() | Adds a value to the assertion counter. | PHPUnit_Framework_TestCase
anything() | Returns a PHPUnit_Framework_Constraint_IsAnything matcher object. | PHPUnit_Framework_Assert
arrayHasKey() | Returns a PHPUnit_Framework_Constraint_ArrayHasKey matcher object. | PHPUnit_Framework_Assert
assertArrayHasKey() | Asserts that an array has a specified key. | PHPUnit_Framework_Assert
assertArrayNotHasKey() | Asserts that an array does not have a specified key. | PHPUnit_Framework_Assert
assertAttributeContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeEquals() | Asserts that a variable is equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeGreaterThan() | Asserts that an attribute is greater than another value. | PHPUnit_Framework_Assert
assertAttributeGreaterThanOrEqual() | Asserts that an attribute is greater than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeLessThan() | Asserts that an attribute is smaller than another value. | PHPUnit_Framework_Assert
assertAttributeLessThanOrEqual() | Asserts that an attribute is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertAttributeNotContains() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotContainsOnly() | Asserts that a haystack that is stored in a static attribute of a class | PHPUnit_Framework_Assert
assertAttributeNotEquals() | Asserts that a variable is not equal to an attribute of an object. | PHPUnit_Framework_Assert
assertAttributeNotSame() | Asserts that a variable and an attribute of an object do not have the | PHPUnit_Framework_Assert
assertAttributeNotType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertAttributeSame() | Asserts that a variable and an attribute of an object have the same type | PHPUnit_Framework_Assert
assertAttributeType() | Asserts that an attribute is of a given type. | PHPUnit_Framework_Assert
assertClassHasAttribute() | Asserts that a class has a specified attribute. | PHPUnit_Framework_Assert
assertClassHasStaticAttribute() | Asserts that a class has a specified static attribute. | PHPUnit_Framework_Assert
assertClassNotHasAttribute() | Asserts that a class does not have a specified attribute. | PHPUnit_Framework_Assert
assertClassNotHasStaticAttribute() | Asserts that a class does not have a specified static attribute. | PHPUnit_Framework_Assert
assertContains() | Asserts that a haystack contains a needle. | PHPUnit_Framework_Assert
assertContainsOnly() | Asserts that a haystack contains only values of a given type. | PHPUnit_Framework_Assert
assertElementContainsText() | Asserts that an element contains a given string. | PHPUnit_Extensions_SeleniumTestCase
assertElementNotContainsText() | Asserts that an element does not contain a given string. | PHPUnit_Extensions_SeleniumTestCase
assertElementValueContains() | Asserts that an element's value contains a given string. | PHPUnit_Extensions_SeleniumTestCase
assertElementValueEquals() | Asserts that an element's value is equal to a given string. | PHPUnit_Extensions_SeleniumTestCase
assertElementValueNotContains() | Asserts that an element's value does not contain a given string. | PHPUnit_Extensions_SeleniumTestCase
assertElementValueNotEquals() | Asserts that an element's value is not equal to a given string. | PHPUnit_Extensions_SeleniumTestCase
assertEqualXMLStructure() | Asserts that a hierarchy of DOMNodes matches. | PHPUnit_Framework_Assert
assertEquals() | Asserts that two variables are equal. | PHPUnit_Framework_Assert
assertFalse() | Asserts that a condition is false. | PHPUnit_Framework_Assert
assertFileEquals() | Asserts that the contents of one file is equal to the contents of another | PHPUnit_Framework_Assert
assertFileExists() | Asserts that a file exists. | PHPUnit_Framework_Assert
assertFileNotEquals() | Asserts that the contents of one file is not equal to the contents of | PHPUnit_Framework_Assert
assertFileNotExists() | Asserts that a file does not exist. | PHPUnit_Framework_Assert
assertGreaterThan() | Asserts that a value is greater than another value. | PHPUnit_Framework_Assert
assertGreaterThanOrEqual() | Asserts that a value is greater than or equal to another value. | PHPUnit_Framework_Assert
assertIsNotSelected() | Asserts that a specific value is not selected. | PHPUnit_Extensions_SeleniumTestCase
assertIsSelected() | Asserts that a specific value is selected. | PHPUnit_Extensions_SeleniumTestCase
assertLessThan() | Asserts that a value is smaller than another value. | PHPUnit_Framework_Assert
assertLessThanOrEqual() | Asserts that a value is smaller than or equal to another value. | PHPUnit_Framework_Assert
assertNotContains() | Asserts that a haystack does not contain a needle. | PHPUnit_Framework_Assert
assertNotContainsOnly() | Asserts that a haystack does not contain only values of a given type. | PHPUnit_Framework_Assert
assertNotEquals() | Asserts that two variables are not equal. | PHPUnit_Framework_Assert
assertNotNull() | Asserts that a variable is not NULL. | PHPUnit_Framework_Assert
assertNotRegExp() | Asserts that a string does not match a given regular expression. | PHPUnit_Framework_Assert
assertNotSame() | Asserts that two variables do not have the same type and value. | PHPUnit_Framework_Assert
assertNotSelected() | Asserts that a specific label is not selected. | PHPUnit_Extensions_SeleniumTestCase
assertNotTag() | This assertion is the exact opposite of assertTag(). | PHPUnit_Framework_Assert
assertNotType() | Asserts that a variable is not of a given type. | PHPUnit_Framework_Assert
assertNull() | Asserts that a variable is NULL. | PHPUnit_Framework_Assert
assertObjectHasAttribute() | Asserts that an object has a specified attribute. | PHPUnit_Framework_Assert
assertObjectNotHasAttribute() | Asserts that an object does not have a specified attribute. | PHPUnit_Framework_Assert
assertRegExp() | Asserts that a string matches a given regular expression. | PHPUnit_Framework_Assert
assertSame() | Asserts that two variables have the same type and value. | PHPUnit_Framework_Assert
assertSelectCount() | Assert the presence, absence, or count of elements in a document matching | PHPUnit_Framework_Assert
assertSelectEquals() | assertSelectEquals("#binder .name", "Chuck", true, $xml); // any? | PHPUnit_Framework_Assert
assertSelectHasOption() | Asserts that a select element has a specific option. | PHPUnit_Extensions_SeleniumTestCase
assertSelectNotHasOption() | Asserts that a select element does not have a specific option. | PHPUnit_Extensions_SeleniumTestCase
assertSelectRegExp() | assertSelectRegExp("#binder .name", "/Mike|Derek/", true, $xml); // any? | PHPUnit_Framework_Assert
assertSelected() | Asserts that a specific label is selected. | PHPUnit_Extensions_SeleniumTestCase
assertStringEndsNotWith() | Asserts that a string ends not with a given prefix. | PHPUnit_Framework_Assert
assertStringEndsWith() | Asserts that a string ends with a given prefix. | PHPUnit_Framework_Assert
assertStringEqualsFile() | Asserts that the contents of a string is equal | PHPUnit_Framework_Assert
assertStringNotEqualsFile() | Asserts that the contents of a string is not equal | PHPUnit_Framework_Assert
assertStringStartsNotWith() | Asserts that a string starts not with a given prefix. | PHPUnit_Framework_Assert
assertStringStartsWith() | Asserts that a string starts with a given prefix. | PHPUnit_Framework_Assert
assertTag() | Evaluate an HTML or XML string and assert its structure and/or contents. | PHPUnit_Framework_Assert
assertThat() | Evaluates a PHPUnit_Framework_Constraint matcher object. | PHPUnit_Framework_Assert
assertTrue() | Asserts that a condition is true. | PHPUnit_Framework_Assert
assertType() | Asserts that a variable is of a given type. | PHPUnit_Framework_Assert
assertXmlFileEqualsXmlFile() | Asserts that two XML files are equal. | PHPUnit_Framework_Assert
assertXmlFileNotEqualsXmlFile() | Asserts that two XML files are not equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlFile() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringEqualsXmlString() | Asserts that two XML documents are equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlFile() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
assertXmlStringNotEqualsXmlString() | Asserts that two XML documents are not equal. | PHPUnit_Framework_Assert
attribute() | Returns a PHPUnit_Framework_Constraint_Attribute matcher object. | PHPUnit_Framework_Assert
attributeEqualTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object | PHPUnit_Framework_Assert
classHasAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasAttribute matcher object. | PHPUnit_Framework_Assert
classHasStaticAttribute() | Returns a PHPUnit_Framework_Constraint_ClassHasStaticAttribute matcher | PHPUnit_Framework_Assert
contains() | Returns a PHPUnit_Framework_Constraint_TraversableContains matcher | PHPUnit_Framework_Assert
containsOnly() | Returns a PHPUnit_Framework_Constraint_TraversableContainsOnly matcher | PHPUnit_Framework_Assert
count() | Counts the number of test cases executed by run(TestResult result). | PHPUnit_Framework_TestCase
equalTo() | Returns a PHPUnit_Framework_Constraint_IsEqual matcher object. | PHPUnit_Framework_Assert
fail() | Fails a test with the given message. | PHPUnit_Framework_Assert
fileExists() | Returns a PHPUnit_Framework_Constraint_FileExists matcher object. | PHPUnit_Framework_Assert
getAnnotations() | Returns the annotations for this test. | PHPUnit_Framework_TestCase
getCount() | Return the current assertion count. | PHPUnit_Framework_Assert
getExpectedException() |  | PHPUnit_Framework_TestCase
getFixtureData() |  | CWebTestCase
getFixtureManager() |  | CWebTestCase
getFixtureRecord() |  | CWebTestCase
getName() | Gets the name of a TestCase. | PHPUnit_Framework_TestCase
getNumAssertions() | Returns the number of assertions performed by this test. | PHPUnit_Framework_TestCase
getResult() |  | PHPUnit_Framework_TestCase
getStatus() | Returns the status of this test. | PHPUnit_Framework_TestCase
getStatusMessage() | Returns the status message of this test. | PHPUnit_Framework_TestCase
greaterThan() | Returns a PHPUnit_Framework_Constraint_GreaterThan matcher object. | PHPUnit_Framework_Assert
greaterThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
hasFailed() | Returns whether or not this test has failed. | PHPUnit_Framework_TestCase
identicalTo() | Returns a PHPUnit_Framework_Constraint_IsIdentical matcher object. | PHPUnit_Framework_Assert
isFalse() | Returns a PHPUnit_Framework_Constraint_IsFalse matcher object. | PHPUnit_Framework_Assert
isInstanceOf() | Returns a PHPUnit_Framework_Constraint_IsInstanceOf matcher object. | PHPUnit_Framework_Assert
isNull() | Returns a PHPUnit_Framework_Constraint_IsNull matcher object. | PHPUnit_Framework_Assert
isTrue() | Returns a PHPUnit_Framework_Constraint_IsTrue matcher object. | PHPUnit_Framework_Assert
isType() | Returns a PHPUnit_Framework_Constraint_IsType matcher object. | PHPUnit_Framework_Assert
lessThan() | Returns a PHPUnit_Framework_Constraint_LessThan matcher object. | PHPUnit_Framework_Assert
lessThanOrEqual() | Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps | PHPUnit_Framework_Assert
logicalAnd() | Returns a PHPUnit_Framework_Constraint_And matcher object. | PHPUnit_Framework_Assert
logicalNot() | Returns a PHPUnit_Framework_Constraint_Not matcher object. | PHPUnit_Framework_Assert
logicalOr() | Returns a PHPUnit_Framework_Constraint_Or matcher object. | PHPUnit_Framework_Assert
logicalXor() | Returns a PHPUnit_Framework_Constraint_Xor matcher object. | PHPUnit_Framework_Assert
markTestIncomplete() | Mark the test as incomplete. | PHPUnit_Framework_Assert
markTestSkipped() | Mark the test as skipped. | PHPUnit_Framework_Assert
matchesRegularExpression() | Returns a PHPUnit_Framework_Constraint_PCREMatch matcher object. | PHPUnit_Framework_Assert
objectHasAttribute() | Returns a PHPUnit_Framework_Constraint_ObjectHasAttribute matcher object. | PHPUnit_Framework_Assert
readAttribute() | Returns the value of an attribute of a class or an object. | PHPUnit_Framework_Assert
resetCount() | Reset the assertion counter. | PHPUnit_Framework_Assert
run() | Runs the test case and collects the results in a TestResult object. | PHPUnit_Extensions_SeleniumTestCase
runBare() | Runs the bare test sequence. | PHPUnit_Framework_TestCase
runDefaultAssertions() |  | PHPUnit_Extensions_SeleniumTestCase
runSelenese() | Runs a test from a Selenese (HTML) specification. | PHPUnit_Extensions_SeleniumTestCase
setAutoStop() |  | PHPUnit_Extensions_SeleniumTestCase
setBackupGlobals() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setBackupStaticAttributes() | Calling this method in setUp() has no effect! | PHPUnit_Framework_TestCase
setDependencies() | Sets the dependencies of a TestCase. | PHPUnit_Framework_TestCase
setDependencyInput() | Sets | PHPUnit_Framework_TestCase
setExpectedException() |  | PHPUnit_Framework_TestCase
setInIsolation() |  | PHPUnit_Framework_TestCase
setName() | Sets the name of a TestCase. | PHPUnit_Framework_TestCase
setPreserveGlobalState() |  | PHPUnit_Framework_TestCase
setResult() |  | PHPUnit_Framework_TestCase
setRunTestInSeparateProcess() |  | PHPUnit_Framework_TestCase
setSharedFixture() | Sets the shared fixture. | PHPUnit_Framework_TestCase
setUpBeforeClass() | This method is called before the first test of this test class is run. | PHPUnit_Framework_TestCase
setUseErrorHandler() |  | PHPUnit_Framework_TestCase
setUseOutputBuffering() |  | PHPUnit_Framework_TestCase
stringContains() | Returns a PHPUnit_Framework_Constraint_StringContains matcher object. | PHPUnit_Framework_Assert
stringEndsWith() | Returns a PHPUnit_Framework_Constraint_StringEndsWith matcher object. | PHPUnit_Framework_Assert
stringStartsWith() | Returns a PHPUnit_Framework_Constraint_StringStartsWith matcher object. | PHPUnit_Framework_Assert
suite() |  | PHPUnit_Extensions_SeleniumTestCase
tearDownAfterClass() | This method is called after the last test of this test class is run. | PHPUnit_Framework_TestCase
toString() | Returns a string representation of the test case. | PHPUnit_Extensions_SeleniumTestCase

Protected Methods

Hide inherited methods

Method | Description | Defined By
any() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
assertPostConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
assertPreConditions() | Performs assertions shared by all tests of a test case. | PHPUnit_Framework_TestCase
at() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
atLeastOnce() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
createResult() | Creates a default TestResult object. | PHPUnit_Framework_TestCase
dataToString() |  | PHPUnit_Framework_TestCase
defaultAssertions() | Template Method that is called after Selenium actions. | PHPUnit_Extensions_SeleniumTestCase
exactly() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
explodeDirectories() |  | PHPUnit_Extensions_SeleniumTestCase
findDirectorySeparator() |  | PHPUnit_Extensions_SeleniumTestCase
getCodeCoverage() |  | PHPUnit_Extensions_SeleniumTestCase
getDataSetAsString() | Gets the data set description of a TestCase. | PHPUnit_Framework_TestCase
getDriver() |  | PHPUnit_Extensions_SeleniumTestCase
getMock() | Returns a mock object for the specified class. | PHPUnit_Framework_TestCase
getMockForAbstractClass() | Returns a mock object for the specified abstract class with all abstract | PHPUnit_Framework_TestCase
getMockFromWsdl() | Returns a mock object based on the given WSDL file. | PHPUnit_Framework_TestCase
getSeleneseFiles() |  | PHPUnit_Extensions_SeleniumTestCase
iniSet() | This method is a wrapper for the ini_set() function that automatically | PHPUnit_Framework_TestCase
matchLocalAndRemotePaths() |  | PHPUnit_Extensions_SeleniumTestCase
never() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
onConsecutiveCalls() |  | PHPUnit_Framework_TestCase
onNotSuccessfulTest() | This method is called when a test method did not execute successfully. | PHPUnit_Extensions_SeleniumTestCase
once() | Returns a matcher that matches when the method it is evaluated for | PHPUnit_Framework_TestCase
prepareTemplate() | Performs custom preparations on the process isolation template. | PHPUnit_Framework_TestCase
returnArgument() |  | PHPUnit_Framework_TestCase
returnCallback() |  | PHPUnit_Framework_TestCase
returnValue() |  | PHPUnit_Framework_TestCase
runTest() |  | PHPUnit_Extensions_SeleniumTestCase
setExpectedExceptionFromAnnotation() |  | PHPUnit_Framework_TestCase
setLocale() | This method is a wrapper for the setlocale() function that automatically | PHPUnit_Framework_TestCase
setUp() | Sets up the fixture before executing a test method. | CWebTestCase
setUseErrorHandlerFromAnnotation() |  | PHPUnit_Framework_TestCase
setUseOutputBufferingFromAnnotation() |  | PHPUnit_Framework_TestCase
tearDown() | Tears down the fixture, for example, close a network connection. | PHPUnit_Framework_TestCase
throwException() |  | PHPUnit_Framework_TestCase

Property Details

fixtures property
protected array $fixtures;

a list of fixtures that should be loaded before each test method executes. The array keys are fixture names, and the array values are either AR class names or table names. If table names, they must begin with a colon character (e.g. 'Post' means an AR class, while ':Post' means a table name). Defaults to false, meaning fixtures will not be used at all.

Method Details

__call() method
public mixed __call(string $name, string $params)
$name | string | method name
$params | string | method parameters
{return} | mixed | the property value

PHP magic method. This method is overridden so that named fixture ActiveRecord instances can be accessed in terms of a method call.

__get() method
public mixed __get(string $name)
$name | string | the property name
{return} | mixed | the property value

PHP magic method. This method is overridden so that named fixture data can be accessed like a normal property.

getFixtureData() method
public array getFixtureData(string $name)
$name | string | the fixture name (the key value in fixtures).
{return} | array | the named fixture data

getFixtureManager() method
public CDbFixtureManager getFixtureManager()
{return} CDbFixtureManager the database fixture manager

getFixtureRecord() method
public CActiveRecord getFixtureRecord(string $name, string $alias)
$name | string | the fixture name (the key value in fixtures).
$alias | string | the alias of the fixture data row
{return} | CActiveRecord | the ActiveRecord instance corresponding to the specified alias in the named fixture. False is returned if there is no such fixture or the record cannot be found.

setUp() method
protected void setUp()

Sets up the fixture before executing a test method. If you override this method, make sure the parent implementation is invoked. Otherwise, the database fixtures will not be managed properly.


CDateTimeParser

All Packages | Methods
Package | system.utils
Inheritance | class CDateTimeParser
Since | 1.0
Version | $Id: CDateTimeParser.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDateTimeParser converts a date/time string to a UNIX timestamp according to the specified pattern.

The following pattern characters are recognized:
Pattern |      Description
----------------------------------------------------
d       | Day of month 1 to 31, no padding
dd      | Day of month 01 to 31, zero leading
M       | Month digit 1 to 12, no padding
MM      | Month digit 01 to 12, zero leading
yy      | 2 year digit, e.g., 96, 05
yyyy    | 4 year digit, e.g., 2005
h       | Hour in 0 to 23, no padding (since version 1.0.5)
hh      | Hour in 00 to 23, zero leading (since version 1.0.5)
H       | Hour in 0 to 23, no padding (since version 1.0.9)
HH      | Hour in 00 to 23, zero leading (since version 1.0.9)
m       | Minutes in 0 to 59, no padding (since version 1.0.5)
mm      | Minutes in 00 to 59, zero leading (since version 1.0.5)
s	   | Seconds in 0 to 59, no padding (since version 1.0.5)
ss      | Seconds in 00 to 59, zero leading (since version 1.0.5)
----------------------------------------------------
All other characters must appear in the date string at the corresponding positions.

For example, to parse a date string '21/10/2008', use the following:
$timestamp=CDateTimeParser::parse('21/10/2008','dd/MM/yyyy');

To format a timestamp to a date string, please use CDateFormatter.

Public Methods

Hide inherited methods

Method | Description | Defined By
parse() | Converts a date string to a timestamp. | CDateTimeParser

Protected Methods

Hide inherited methods

Method | Description | Defined By
parseInteger() |  | CDateTimeParser

Method Details

parse() method
public static integer parse(string $value, string $pattern='MM/dd/yyyy')
$value | string | the date string to be parsed
$pattern | string | the pattern that the date string is following
{return} | integer | timestamp for the date string. False if parsing fails.

Converts a date string to a timestamp.

parseInteger() method
protected static void parseInteger($value, $offset, $minLength, $maxLength)
$value
$offset
$minLength
$maxLength


CFileHelper

All Packages | Methods
Package | system.utils
Inheritance | class CFileHelper
Since | 1.0
Version | $Id: CFileHelper.php 1832 2010-02-20 03:22:45Z qiang.xue $
CFileHelper provides a set of helper methods for common file system operations.

Public Methods

Hide inherited methods

Method | Description | Defined By
copyDirectory() | Copies a directory recursively as another. | CFileHelper
findFiles() | Returns the files found under the specified directory and subdirectories. | CFileHelper
getMimeType() | Determines the MIME type of the specified file. | CFileHelper
getMimeTypeByExtension() | Determines the MIME type based on the extension name of the specified file. | CFileHelper

Protected Methods

Hide inherited methods

Method | Description | Defined By
copyDirectoryRecursive() | Copies a directory. | CFileHelper
findFilesRecursive() | Returns the files found under the specified directory and subdirectories. | CFileHelper
validatePath() | Validates a file or directory. | CFileHelper

Method Details

copyDirectory() method
public static void copyDirectory(string $src, string $dst, array $options=array ( ))
$src | string | the source directory
$dst | string | the destination directory
$options array options for directory copy. Valid options are:
  • fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be copied.
  • exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'.
  • level: integer, recursion depth, default=-1. Level -1 means copying all directories and files under the directory; Level 0 means copying only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.

Copies a directory recursively as another. If the destination directory does not exist, it will be created.

copyDirectoryRecursive() method
protected static void copyDirectoryRecursive(string $src, string $dst, string $base, array $fileTypes, array $exclude, integer $level)
$src | string | the source directory
$dst | string | the destination directory
$base | string | the path relative to the original source directory
$fileTypes | array | list of file name suffix (without dot). Only files with these suffixes will be copied.
$exclude | array | list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'.
$level | integer | recursion depth. It defaults to -1. Level -1 means copying all directories and files under the directory; Level 0 means copying only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.

Copies a directory. This method is mainly used by copyDirectory.

findFiles() method
public static array findFiles(string $dir, array $options=array ( ))
$dir | string | the directory under which the files will be looked for
$options array options for file searching. Valid options are:
  • fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be returned.
  • exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'.
  • level: integer, recursion depth, default=-1. Level -1 means searching for all directories and files under the directory; Level 0 means searching for only the files DIRECTLY under the directory; level N means searching for those directories that are within N levels.
{return} | array | files found under the directory. The file list is sorted.

Returns the files found under the specified directory and subdirectories.

findFilesRecursive() method
protected static array findFilesRecursive(string $dir, string $base, array $fileTypes, array $exclude, integer $level)
$dir | string | the source directory
$base | string | the path relative to the original source directory
$fileTypes | array | list of file name suffix (without dot). Only files with these suffixes will be returned.
$exclude | array | list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'.
$level | integer | recursion depth. It defaults to -1. Level -1 means searching for all directories and files under the directory; Level 0 means searching for only the files DIRECTLY under the directory; level N means searching for those directories that are within N levels.
{return} | array | files found under the directory.

Returns the files found under the specified directory and subdirectories. This method is mainly used by findFiles.

getMimeType() method
public static string getMimeType(string $file)
$file | string | the file name.
{return} | string | the MIME type. Null is returned if the MIME type cannot be determined.

Determines the MIME type of the specified file. This method will attempt the following approaches in order:

  1. finfo
  2. mime_content_type
  3. getMimeTypeByExtension

getMimeTypeByExtension() method
public static string getMimeTypeByExtension(string $file)
$file | string | the file name.
{return} | string | the MIME type. Null is returned if the MIME type cannot be determined.

Determines the MIME type based on the extension name of the specified file. This method will use a local map between extension name and MIME type.

validatePath() method
protected static boolean validatePath(string $base, string $file, boolean $isFile, array $fileTypes, array $exclude)
$base | string | the path relative to the original source directory
$file | string | the file or directory name
$isFile | boolean | whether this is a file
$fileTypes | array | list of file name suffix (without dot). Only files with these suffixes will be copied.
$exclude | array | list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'.
{return} | boolean | whether the file or directory is valid

Validates a file or directory.


CFormatter

Package | system.utils
Inheritance | class CFormatter » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.1.0
Version | $Id: CFormatter.php 1716 2010-01-17 21:38:41Z qiang.xue $
CFormatter provides a set of commonly used data formatting methods.

The formatting methods provided by CFormatter are all named in the form of formatXyz. The behavior of some of them may be configured via the properties of CFormatter. For example, by configuring dateFormat, one may control how formatDate formats the value into a date string.

For convenience, CFormatter also implements the mechanism of calling formatting methods with their shortcuts (called types). In particular, if a formatting method is named formatXyz, then its shortcut method is xyz (case-insensitive). For example, calling $formatter->date($value) is equivalent to calling $formatter->formatDate($value).

Currently, the following types are recognizable:
  • raw: the attribute value will not be changed at all.
  • text: the attribute value will be HTML-encoded when rendering.
  • ntext: the formatNtext method will be called to format the attribute value as a HTML-encoded plain text with newlines converted as the HTML <br /> tags.
  • html: the attribute value will be purified and then returned.
  • date: the formatDate method will be called to format the attribute value as a date.
  • time: the formatTime method will be called to format the attribute value as a time.
  • datetime: the formatDatetime method will be called to format the attribute value as a date with time.
  • boolean: the formatBoolean method will be called to format the attribute value as a boolean display.
  • number: the formatNumber method will be called to format the attribute value as a number display.
  • email: the formatEmail method will be called to format the attribute value as a mailto link.
  • image: the formatImage method will be called to format the attribute value as an image tag where the attribute value is the image URL.
  • url: the formatUrl method will be called to format the attribute value as a hyperlink where the attribute value is the URL.

By default, CApplication registers CFormatter as an application component whose ID is 'format'. Therefore, one may call Yii::app()->format->boolean(1).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
booleanFormat | array | the text to be displayed when formatting a boolean value. | CFormatter
dateFormat | string | the format string to be used to format a date using PHP date() function. | CFormatter
datetimeFormat | string | the format string to be used to format a date and time using PHP date() function. | CFormatter
htmlPurifier | CHtmlPurifier | the HTML purifier instance | CFormatter
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
numberFormat | array | the format used to format a number with PHP number_format() function. | CFormatter
timeFormat | string | the format string to be used to format a time using PHP date() function. | CFormatter

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the format method when its shortcut is invoked. | CFormatter
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
format() | Formats a value based on the given type. | CFormatter
formatBoolean() | Formats the value as a boolean. | CFormatter
formatDate() | Formats the value as a date. | CFormatter
formatDatetime() | Formats the value as a date and time. | CFormatter
formatEmail() | Formats the value as a mailto link. | CFormatter
formatHtml() | Formats the value as HTML text without any encoding. | CFormatter
formatImage() | Formats the value as an image tag. | CFormatter
formatNtext() | Formats the value as a HTML-encoded plain text and converts newlines with HTML br tags. | CFormatter
formatNumber() | Formats the value as a number using PHP number_format() function. | CFormatter
formatRaw() | Formats the value as is without any formatting. | CFormatter
formatText() | Formats the value as a HTML-encoded plain text. | CFormatter
formatTime() | Formats the value as a time. | CFormatter
formatUrl() | Formats the value as a hyperlink. | CFormatter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHtmlPurifier() |  | CFormatter
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent

Property Details

booleanFormat property
public array $booleanFormat;

the text to be displayed when formatting a boolean value. The first element corresponds to the text display for false, the second element for true. Defaults to array('No', 'Yes').

dateFormat property
public string $dateFormat;

the format string to be used to format a date using PHP date() function. Defaults to 'Y/m/d'.

datetimeFormat property
public string $datetimeFormat;

the format string to be used to format a date and time using PHP date() function. Defaults to 'Y/m/d h:i:s A'.

htmlPurifier property read-only
public CHtmlPurifier getHtmlPurifier()

the HTML purifier instance

numberFormat property
public array $numberFormat;

the format used to format a number with PHP number_format() function. Three elements may be specified: "decimals", "decimalSeparator" and "thousandSeparator". They correspond to the number of digits after the decimal point, the character displayed as the decimal point, and the thousands separator character.

timeFormat property
public string $timeFormat;

the format string to be used to format a time using PHP date() function. Defaults to 'h:i:s A'.

Method Details

__call() method
public mixed __call(string $name, array $parameters)
$name | string | the method name
$parameters | array | method parameters
{return} | mixed | the method return value

Calls the format method when its shortcut is invoked. This is a PHP magic method that we override to implement the shortcut format methods.

format() method
public string format(mixed $value, string $type)
$value | mixed | the value to be formatted
$type | string | the data type. This must correspond to a format method available in CFormatter. For example, we can use 'text' here because there is method named formatText.
{return} | string | the formatted data

Formats a value based on the given type.

formatBoolean() method
public string formatBoolean(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a boolean.

See Also

  • trueText
  • falseText
formatDate() method
public string formatDate(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a date.

See Also

  • dateFormat
formatDatetime() method
public string formatDatetime(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a date and time.

See Also

  • datetimeFormat
formatEmail() method
public string formatEmail(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a mailto link.

formatHtml() method
public string formatHtml(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as HTML text without any encoding.

formatImage() method
public string formatImage(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as an image tag.

formatNtext() method
public string formatNtext(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a HTML-encoded plain text and converts newlines with HTML br tags.

formatNumber() method
public string formatNumber(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a number using PHP number_format() function.

See Also

  • numberFormat
formatRaw() method
public string formatRaw(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as is without any formatting. This method simply returns back the parameter without any format.

formatText() method
public string formatText(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a HTML-encoded plain text.

formatTime() method
public string formatTime(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a time.

See Also

  • timeFormat
formatUrl() method
public string formatUrl(mixed $value)
$value | mixed | the value to be formatted
{return} | string | the formatted result

Formats the value as a hyperlink.

getHtmlPurifier() method
public CHtmlPurifier getHtmlPurifier()
{return} CHtmlPurifier the HTML purifier instance


CMarkdownParser

Package | system.utils
Inheritance | class CMarkdownParser » MarkdownExtra_Parser » Markdown_Parser
Since | 1.0
Version | $Id: CMarkdownParser.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMarkdownParser is a wrapper of MarkdownExtra_Parser.

CMarkdownParser extends MarkdownExtra_Parser by using Text_Highlighter to highlight code blocks with specific language syntax. In particular, if a code block starts with the following:
[language]
The syntax for the specified language will be used to highlight code block. The languages supported include (case-insensitive): ABAP, CPP, CSS, DIFF, DTD, HTML, JAVA, JAVASCRIPT, MYSQL, PERL, PHP, PYTHON, RUBY, SQL, XML

You can also specify options to be passed to the syntax highlighter. For example:
[php showLineNumbers=1]
which will show line numbers in each line of the code block.

For details about the standard markdown syntax, please check the following:
  • official markdown syntax
  • markdown extra syntax

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
abbr_desciptions |  |  | MarkdownExtra_Parser
abbr_word_re |  |  | MarkdownExtra_Parser
auto_close_tags_re |  |  | MarkdownExtra_Parser
block_gamut |  |  | Markdown_Parser
block_tags_re |  |  | MarkdownExtra_Parser
clean_tags_re |  |  | MarkdownExtra_Parser
contain_span_tags_re |  |  | MarkdownExtra_Parser
context_block_tags_re |  |  | MarkdownExtra_Parser
document_gamut |  |  | Markdown_Parser
em_relist |  |  | Markdown_Parser
em_strong_prepared_relist |  |  | Markdown_Parser
em_strong_relist |  |  | Markdown_Parser
empty_element_suffix |  |  | Markdown_Parser
escape_chars |  |  | Markdown_Parser
escape_chars_re |  |  | Markdown_Parser
fn_backlink_class |  |  | MarkdownExtra_Parser
fn_backlink_title |  |  | MarkdownExtra_Parser
fn_id_prefix |  |  | MarkdownExtra_Parser
fn_link_class |  |  | MarkdownExtra_Parser
fn_link_title |  |  | MarkdownExtra_Parser
footnote_counter |  |  | MarkdownExtra_Parser
footnotes |  |  | MarkdownExtra_Parser
footnotes_ordered |  |  | MarkdownExtra_Parser
highlightCssClass | string | the css class for the div element containing the code block that is highlighted. | CMarkdownParser
html_hashes |  |  | Markdown_Parser
in_anchor |  |  | Markdown_Parser
list_level |  |  | Markdown_Parser
nested_brackets_depth |  |  | Markdown_Parser
nested_brackets_re |  |  | Markdown_Parser
nested_url_parenthesis_depth |  |  | Markdown_Parser
nested_url_parenthesis_re |  |  | Markdown_Parser
no_entities |  |  | Markdown_Parser
no_markup |  |  | Markdown_Parser
predef_abbr |  |  | MarkdownExtra_Parser
predef_titles |  |  | Markdown_Parser
predef_urls |  |  | Markdown_Parser
span_gamut |  |  | Markdown_Parser
strong_relist |  |  | Markdown_Parser
tab_width |  |  | Markdown_Parser
titles |  |  | Markdown_Parser
urls |  |  | Markdown_Parser
utf8_strlen |  |  | Markdown_Parser

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() |  | MarkdownExtra_Parser
_appendFootnotes_callback() |  | MarkdownExtra_Parser
_detab_callback() |  | Markdown_Parser
_doAbbreviations_callback() |  | MarkdownExtra_Parser
_doAnchors_inline_callback() |  | Markdown_Parser
_doAnchors_reference_callback() |  | Markdown_Parser
_doAutoLinks_email_callback() |  | Markdown_Parser
_doAutoLinks_url_callback() |  | Markdown_Parser
_doBlockQuotes_callback() |  | Markdown_Parser
_doBlockQuotes_callback2() |  | Markdown_Parser
_doCodeBlocks_callback() | Callback function when a code block is matched. | CMarkdownParser
_doDefLists_callback() |  | MarkdownExtra_Parser
_doFencedCodeBlocks_callback() | Callback function when a fenced code block is matched. | CMarkdownParser
_doFencedCodeBlocks_newlines() |  | MarkdownExtra_Parser
_doHardBreaks_callback() |  | Markdown_Parser
_doHeaders_attr() |  | MarkdownExtra_Parser
_doHeaders_callback_atx() |  | MarkdownExtra_Parser
_doHeaders_callback_setext() |  | MarkdownExtra_Parser
_doImages_inline_callback() |  | Markdown_Parser
_doImages_reference_callback() |  | Markdown_Parser
_doLists_callback() |  | Markdown_Parser
_doTable_callback() |  | MarkdownExtra_Parser
_doTable_leadingPipe_callback() |  | MarkdownExtra_Parser
_hashHTMLBlocks_callback() |  | Markdown_Parser
_hashHTMLBlocks_inHTML() |  | MarkdownExtra_Parser
_hashHTMLBlocks_inMarkdown() |  | MarkdownExtra_Parser
_initDetab() |  | Markdown_Parser
_processDefListItems_callback_dd() |  | MarkdownExtra_Parser
_processDefListItems_callback_dt() |  | MarkdownExtra_Parser
_processListItems_callback() |  | Markdown_Parser
_stripAbbreviations_callback() |  | MarkdownExtra_Parser
_stripFootnotes_callback() |  | MarkdownExtra_Parser
_stripLinkDefinitions_callback() |  | Markdown_Parser
_unhash_callback() |  | Markdown_Parser
appendFootnotes() |  | MarkdownExtra_Parser
detab() |  | Markdown_Parser
doAbbreviations() |  | MarkdownExtra_Parser
doAnchors() |  | Markdown_Parser
doAutoLinks() |  | Markdown_Parser
doBlockQuotes() |  | Markdown_Parser
doCodeBlocks() |  | Markdown_Parser
doDefLists() |  | MarkdownExtra_Parser
doFencedCodeBlocks() |  | MarkdownExtra_Parser
doFootnotes() |  | MarkdownExtra_Parser
doHardBreaks() |  | Markdown_Parser
doHeaders() |  | MarkdownExtra_Parser
doHorizontalRules() |  | Markdown_Parser
doImages() |  | Markdown_Parser
doItalicsAndBold() |  | Markdown_Parser
doLists() |  | Markdown_Parser
doTables() |  | MarkdownExtra_Parser
encodeAmpsAndAngles() |  | Markdown_Parser
encodeAttribute() |  | Markdown_Parser
encodeEmailAddress() |  | Markdown_Parser
formParagraphs() |  | MarkdownExtra_Parser
getDefaultCssFile() |  | CMarkdownParser
getHiglightConfig() | Generates the config for the highlighter. | CMarkdownParser
handleSpanToken() |  | Markdown_Parser
hashBlock() |  | Markdown_Parser
hashClean() |  | MarkdownExtra_Parser
hashHTMLBlocks() |  | MarkdownExtra_Parser
hashPart() |  | Markdown_Parser
makeCodeSpan() |  | Markdown_Parser
outdent() |  | Markdown_Parser
parseSpan() |  | Markdown_Parser
prepareItalicsAndBold() |  | Markdown_Parser
processDefListItems() |  | MarkdownExtra_Parser
processListItems() |  | Markdown_Parser
runBasicBlockGamut() |  | Markdown_Parser
runBlockGamut() |  | Markdown_Parser
runSpanGamut() |  | Markdown_Parser
safeTransform() | Transforms the content and purifies the result. | CMarkdownParser
setup() |  | MarkdownExtra_Parser
stripAbbreviations() |  | MarkdownExtra_Parser
stripFootnotes() |  | MarkdownExtra_Parser
stripLinkDefinitions() |  | Markdown_Parser
teardown() |  | MarkdownExtra_Parser
transform() |  | Markdown_Parser
unhash() |  | Markdown_Parser

Protected Methods

Hide inherited methods

Method | Description | Defined By
createHighLighter() | Creates a highlighter instance. | CMarkdownParser
getHighlightTag() | Returns the user-entered highlighting options. | CMarkdownParser
getInlineOption() | Retrieves the specified configuration. | CMarkdownParser
highlightCodeBlock() | Highlights the code block. | CMarkdownParser

Property Details

highlightCssClass property
public string $highlightCssClass;

the css class for the div element containing the code block that is highlighted. Defaults to 'hl-code'.

Method Details

_doCodeBlocks_callback() method
public string _doCodeBlocks_callback(array $matches)
$matches | array | matches
{return} | string | the highlighted code block

Callback function when a code block is matched.

_doFencedCodeBlocks_callback() method
public string _doFencedCodeBlocks_callback(array $matches)
$matches | array | matches
{return} | string | the highlighted code block

Callback function when a fenced code block is matched.

createHighLighter() method
protected Text_Highlighter createHighLighter(string $options)
$options | string | the user-entered options
{return} | Text_Highlighter | the highlighter instance

Creates a highlighter instance.

getDefaultCssFile() method
public string getDefaultCssFile()
{return} string the default CSS file that is used to highlight code blocks.

getHighlightTag() method
protected string getHighlightTag(string $codeblock)
$codeblock | string | code block with highlighting options.
{return} | string | the user-entered highlighting options. Null if no option is entered.

Returns the user-entered highlighting options.

getHiglightConfig() method
public array getHiglightConfig(string $options)
$options | string | user-entered options
{return} | array | the highlighter config

Generates the config for the highlighter.

getInlineOption() method
protected mixed getInlineOption(string $name, string $str, mixed $defaultValue)
$name | string | the configuration name
$str | string | the user-entered options
$defaultValue | mixed | default value if the configuration is not present
{return} | mixed | the configuration value

Retrieves the specified configuration.

highlightCodeBlock() method
protected string highlightCodeBlock(string $codeblock)
$codeblock | string | the code block
{return} | string | the highlighted code block. Null if the code block does not need to highlighted

Highlights the code block.

safeTransform() method (available since v1.0.1)
public string safeTransform(string $content)
$content | string | the markdown content
{return} | string | the purified HTML content

Transforms the content and purifies the result. This method calls the transform() method to convert markdown content into HTML content. It then uses CHtmlPurifier to purify the HTML content to avoid XSS attacks.


CPropertyValue

All Packages | Methods
Package | system.utils
Inheritance | class CPropertyValue
Since | 1.0
Version | $Id: CPropertyValue.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPropertyValue is a helper class that provides static methods to convert component property values to specific types.

CPropertyValue is commonly used in component setter methods to ensure the new property value is of the specific type. For example, a boolean-typed property setter method would be as follows,
public function setPropertyName($value)
{
    $value=CPropertyValue::ensureBoolean($value);
    // $value is now of boolean type
}

Properties can be of the following types with specific type conversion rules:
  • string: a boolean value will be converted to 'true' or 'false'.
  • boolean: string 'true' (case-insensitive) will be converted to true, string 'false' (case-insensitive) will be converted to false.
  • integer
  • float
  • array: string starting with '(' and ending with ')' will be considered as as an array expression and will be evaluated. Otherwise, an array with the value to be ensured is returned.
  • object
  • enum: enumerable type, represented by an array of strings.

Public Methods

Hide inherited methods

Method | Description | Defined By
ensureArray() | Converts a value to array type. If the value is a string and it is | CPropertyValue
ensureBoolean() | Converts a value to boolean type. | CPropertyValue
ensureEnum() | Converts a value to enum type. | CPropertyValue
ensureFloat() | Converts a value to float type. | CPropertyValue
ensureInteger() | Converts a value to integer type. | CPropertyValue
ensureObject() | Converts a value to object type. | CPropertyValue
ensureString() | Converts a value to string type. | CPropertyValue

Method Details

ensureArray() method
public static array ensureArray(mixed $value)
$value | mixed | the value to be converted.
{return} | array |

Converts a value to array type. If the value is a string and it is in the form (a,b,c) then an array consisting of each of the elements will be returned. If the value is a string and it is not in this form then an array consisting of just the string will be returned. If the value is not a string then

ensureBoolean() method
public static boolean ensureBoolean(mixed $value)
$value | mixed | the value to be converted.
{return} | boolean |

Converts a value to boolean type. Note, string 'true' (case-insensitive) will be converted to true, string 'false' (case-insensitive) will be converted to false. If a string represents a non-zero number, it will be treated as true.

ensureEnum() method
public static string ensureEnum(string $value, string $enumType)
$value | string | the enumerable value to be checked.
$enumType | string | the enumerable class name (make sure it is included before calling this function).
{return} | string | the valid enumeration value

Converts a value to enum type.

This method checks if the value is of the specified enumerable type. A value is a valid enumerable value if it is equal to the name of a constant in the specified enumerable type (class). For more details about enumerable, see CEnumerable.

ensureFloat() method
public static float ensureFloat(mixed $value)
$value | mixed | the value to be converted.
{return} | float |

Converts a value to float type.

ensureInteger() method
public static integer ensureInteger(mixed $value)
$value | mixed | the value to be converted.
{return} | integer |

Converts a value to integer type.

ensureObject() method
public static object ensureObject(mixed $value)
$value | mixed | the value to be converted.
{return} | object |

Converts a value to object type.

ensureString() method
public static string ensureString(mixed $value)
$value | mixed | the value to be converted.
{return} | string |

Converts a value to string type. Note, a boolean value will be converted to 'true' if it is true and 'false' if it is false.


CTimestamp

All Packages | Methods
Package | system.utils
Inheritance | class CTimestamp
Since | 1.0
Version | $Id: CTimestamp.php 1678 2010-01-07 21:02:00Z qiang.xue $
CTimestamp represents a timestamp.

This class was adapted from the ADOdb Date Library, as part of the ADOdb abstraction library. The original source code was released under both BSD and GNU Lesser GPL library license, with the following copyright notice: Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim All rights reserved.

PHP native date static functions use integer timestamps for computations. Because of this, dates are restricted to the years 1901-2038 on Unix and 1970-2038 on Windows due to integer overflow for dates beyond those years. This library overcomes these limitations by replacing the native static function's signed integers (normally 32-bits) with PHP floating point numbers (normally 64-bits).

Dates from 100 A.D. to 3000 A.D. and later have been tested. The minimum is 100 A.D. as <100 will invoke the 2 => 4 digit year conversion. The maximum is billions of years in the future, but this is a theoretical limit as the computation of that year would take too long with the current implementation of getTimestamp.

PERFORMANCE For high speed, this library uses the native date static functions where possible, and only switches to PHP code when the dates fall outside the 32-bit signed integer range.

Public Methods

Hide inherited methods

Method | Description | Defined By
formatDate() | Formats a timestamp to a date string. | CTimestamp
get4DigitYear() | Returns 4-digit representation of the year. | CTimestamp
getDate() | Returns the getdate() array. | CTimestamp
getDayofWeek() | Gets day of week, 0 = Sunday,... 6=Saturday. | CTimestamp
getGMTDiff() |  | CTimestamp
getTimestamp() | Generates a timestamp. | CTimestamp
isLeapYear() | Checks for leap year, returns true if it is. No 2-digit year check. Also | CTimestamp
isValidDate() | Checks to see if the year, month, day are valid combination. | CTimestamp
isValidTime() | Checks to see if the hour, minute and second are valid. | CTimestamp

Protected Methods

Hide inherited methods

Method | Description | Defined By
digitCheck() | Fix 2-digit years. Works for any century. | CTimestamp

Method Details

digitCheck() method
protected static integer digitCheck(integer $y)
$y | integer | year
{return} | integer | change two digit year into multiple digits

Fix 2-digit years. Works for any century. Assumes that if 2-digit is more than 30 years in future, then previous century.

formatDate() method
public static string formatDate(string $fmt, integer $d=false, boolean $is_gmt=false)
$fmt | string | format pattern
$d | integer | timestamp
$is_gmt | boolean | whether this is a GMT timestamp
{return} | string | formatted date based on timestamp $d

Formats a timestamp to a date string.

get4DigitYear() method
public static integer get4DigitYear(integer $y)
$y | integer | year
{return} | integer | 4-digit representation of the year

Returns 4-digit representation of the year.

getDate() method
public static array getDate(integer $d=false, boolean $fast=false, boolean $gmt=false)
$d | integer | original date timestamp. False to use the current timestamp.
$fast | boolean | false to compute the day of the week, default is true
$gmt | boolean | true to calculate the GMT dates
{return} | array | an array with date info.

Returns the getdate() array.

getDayofWeek() method
public static integer getDayofWeek(integer $year, integer $month, integer $day)
$year | integer | year
$month | integer | month
$day | integer | day
{return} | integer | day of week

Gets day of week, 0 = Sunday,... 6=Saturday. Algorithm from PEAR::Date_Calc

getGMTDiff() method
public static integer getGMTDiff()
{return} integer get local time zone offset from GMT

getTimestamp() method
public static integer|float getTimestamp(integer $hr, integer $min, integer $sec, integer $mon=false, integer $day=false, integer $year=false, boolean $is_gmt=false)
$hr | integer | hour
$min | integer | minute
$sec | integer | second
$mon | integer | month
$day | integer | day
$year | integer | year
$is_gmt | boolean | whether this is GMT time
{return} | integer|float | a timestamp given a local time. Originally by jackbbs.

Generates a timestamp. Not a very fast algorithm - O(n) operation. Could be optimized to O(1).

isLeapYear() method
public static boolean isLeapYear(integer $year)
$year | integer | year to check
{return} | boolean | true if is leap year

Checks for leap year, returns true if it is. No 2-digit year check. Also handles julian calendar correctly.

isValidDate() method
public static boolean isValidDate(integer $y, integer $m, integer $d)
$y | integer | year
$m | integer | month
$d | integer | day
{return} | boolean | true if valid date, semantic check only.

Checks to see if the year, month, day are valid combination.

isValidTime() method (available since v1.0.5)
public static boolean isValidTime(integer $h, integer $m, integer $s, boolean $hs24=true)
$h | integer | hour
$m | integer | minute
$s | integer | second
$hs24 | boolean | whether the hours should be 0 through 23 (default) or 1 through 12.
{return} | boolean | true if valid date, semantic check only.

Checks to see if the hour, minute and second are valid.


CVarDumper

All Packages | Methods
Package | system.utils
Inheritance | class CVarDumper
Since | 1.0
Version | $Id: CVarDumper.php 1762 2010-01-28 14:19:20Z qiang.xue $
CVarDumper is intended to replace the buggy PHP function var_dump and print_r. It can correctly identify the recursively referenced objects in a complex object structure. It also has a recursive depth control to avoid indefinite recursive display of some peculiar variables.

CVarDumper can be used as follows,
CVarDumper::dump($var);

Public Methods

Hide inherited methods

Method | Description | Defined By
dump() | Displays a variable. | CVarDumper
dumpAsString() | Dumps a variable in terms of a string. | CVarDumper

Method Details

dump() method
public static void dump(mixed $var, integer $depth=10, boolean $highlight=false)
$var | mixed | variable to be dumped
$depth | integer | maximum depth that the dumper should go into the variable. Defaults to 10.
$highlight | boolean | whether the result should be syntax-highlighted

Displays a variable. This method achieves the similar functionality as var_dump and print_r but is more robust when handling complex objects such as Yii controllers.

dumpAsString() method
public static string dumpAsString(mixed $var, integer $depth=10, boolean $highlight=false)
$var | mixed | variable to be dumped
$depth | integer | maximum depth that the dumper should go into the variable. Defaults to 10.
$highlight | boolean | whether the result should be syntax-highlighted
{return} | string | the string representation of the variable

Dumps a variable in terms of a string. This method achieves the similar functionality as var_dump and print_r but is more robust when handling complex objects such as Yii controllers.


CBooleanValidator

Package | system.validators
Inheritance | class CBooleanValidator » CValidator » CComponent
Since | 1.0.10
Version | $Id: CBooleanValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CBooleanValidator validates that the attribute value is either trueValue or falseValue.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CBooleanValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
falseValue | mixed | the value representing false status. | CBooleanValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
strict | boolean | whether the comparison to trueValue and falseValue is strict. | CBooleanValidator
trueValue | mixed | the value representing true status. | CBooleanValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CBooleanValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

falseValue property
public mixed $falseValue;

the value representing false status. Defaults to '0'.

strict property
public boolean $strict;

whether the comparison to trueValue and falseValue is strict. When this is true, the attribute value and type must both match those of trueValue or falseValue. Defaults to false, meaning only the value needs to be matched.

trueValue property
public mixed $trueValue;

the value representing true status. Defaults to '1'.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CCaptchaValidator

Package | system.validators
Inheritance | class CCaptchaValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CCaptchaValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.

CCaptchaValidator should be used together with CCaptchaAction.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CCaptchaValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
captchaAction | string | ID of the action that renders the CAPTCHA image. | CCaptchaValidator
caseSensitive | boolean | whether the comparison is case sensitive. | CCaptchaValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CCaptchaValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to false, meaning the attribute is invalid if it is empty.

captchaAction property
public string $captchaAction;

ID of the action that renders the CAPTCHA image. Defaults to 'captcha', meaning the 'captcha' action declared in the current controller. This can also be a route consisting of controller ID and action ID.

caseSensitive property
public boolean $caseSensitive;

whether the comparison is case sensitive. Defaults to false.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CCompareValidator

Package | system.validators
Inheritance | class CCompareValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CCompareValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCompareValidator compares the specified attribute value with another value and validates if they are equal.

The value being compared with can be another attribute value (specified via compareAttribute) or a constant (specified via compareValue. When both are specified, the latter takes precedence. If neither is specified, the attribute will be compared with another attribute whose name is by appending "_repeat" to the source attribute name.

The comparison can be either strict or not.

Starting from version 1.0.8, CCompareValidator supports different comparison operators. Previously, it only compares to see if two values are equal or not.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CCompareValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
compareAttribute | string | the name of the attribute to be compared with | CCompareValidator
compareValue | string | the constant value to be compared with | CCompareValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
operator | string | the operator for comparison. | CCompareValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
strict | boolean | whether the comparison is strict (both value and type must be the same. | CCompareValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CCompareValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to false. If this is true, it means the attribute is considered valid when it is empty.

compareAttribute property
public string $compareAttribute;

the name of the attribute to be compared with

compareValue property
public string $compareValue;

the constant value to be compared with

operator property (available since v1.0.8)
public string $operator;

the operator for comparison. Defaults to '='. The followings are valid operators:

  • '=' or '==': validates to see if the two values are equal. If strict is true, the comparison will be done in strict mode (i.e. checking value type as well).
  • '!=': validates to see if the two values are NOT equal. If strict is true, the comparison will be done in strict mode (i.e. checking value type as well).
  • '>': validates to see if the value being validated is greater than the value being compared with.
  • '>=': validates to see if the value being validated is greater than or equal to the value being compared with.
  • '<': validates to see if the value being validated is less than the value being compared with.
  • '<=': validates to see if the value being validated is less than or equal to the value being compared with.

strict property
public boolean $strict;

whether the comparison is strict (both value and type must be the same.) Defaults to false.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CDefaultValueValidator

Package | system.validators
Inheritance | class CDefaultValueValidator » CValidator » CComponent
Since | 1.0.2
Version | $Id: CDefaultValueValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDefaultValueValidator sets the attributes with the specified value. It does not do validation. Its existence is mainly to allow specifying attribute default values in a dynamic way.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
setOnEmpty | boolean | whether to set the default value only when the attribute value is null or empty string. | CDefaultValueValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
value | mixed | the default value to be set to the specified attributes. | CDefaultValueValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CDefaultValueValidator

Property Details

setOnEmpty property
public boolean $setOnEmpty;

whether to set the default value only when the attribute value is null or empty string. Defaults to true. If false, the attribute will always be assigned with the default value, even if it is already explicitly assigned a value.

value property
public mixed $value;

the default value to be set to the specified attributes.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object.


CEmailValidator

Package | system.validators
Inheritance | class CEmailValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CEmailValidator.php 1840 2010-02-26 04:34:30Z qiang.xue $
CEmailValidator validates that the attribute value is a valid email address.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CEmailValidator
allowName | boolean | whether to allow name in the email address (e. | CEmailValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
checkMX | boolean | whether to check the MX record for the email address. | CEmailValidator
checkPort | boolean | whether to check port 25 for the email address. | CEmailValidator
fullPattern | string | the regular expression used to validate email addresses with the name part. | CEmailValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
pattern | string | the regular expression used to validate the attribute value. | CEmailValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator
validateValue() | Validates a static value to see if it is a valid email. | CEmailValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CEmailValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

allowName property (available since v1.0.5)
public boolean $allowName;

whether to allow name in the email address (e.g. "Qiang Xue "). Defaults to false.

See Also

  • fullPattern
checkMX property
public boolean $checkMX;

whether to check the MX record for the email address. Defaults to false. To enable it, you need to make sure the PHP function 'checkdnsrr' exists in your PHP installation.

checkPort property (available since v1.0.4)
public boolean $checkPort;

whether to check port 25 for the email address. Defaults to false.

fullPattern property (available since v1.0.5)
public string $fullPattern;

the regular expression used to validate email addresses with the name part. This property is used only when allowName is true.

See Also

  • allowName
pattern property
public string $pattern;

the regular expression used to validate the attribute value.

See Also

  • http://www.regular-expressions.info/email.html

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.

validateValue() method (available since v1.1.1)
public boolean validateValue(mixed $value)
$value | mixed | the value to be validated
{return} | boolean | whether the value is a valid email

Validates a static value to see if it is a valid email. Note that this method does not respect allowEmpty property. This method is provided so that you can call it directly without going through the model validation rule mechanism.


CExistValidator

Package | system.validators
Inheritance | class CExistValidator » CValidator » CComponent
Since | 1.0.4
Version | $Id: CExistValidator.php 1881 2010-03-10 22:17:34Z qiang.xue $
CExistValidator validates that the attribute value exists in a table.

This validator is often used to verify that a foreign key contains a value that can be found in the foreign table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CExistValidator
attributeName | string | the ActiveRecord class attribute name that should be used to look for the attribute value being validated. | CExistValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
className | string | the ActiveRecord class name that should be used to look for the attribute value being validated. | CExistValidator
criteria | array | additional query criteria. | CExistValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CExistValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

attributeName property
public string $attributeName;

the ActiveRecord class attribute name that should be used to look for the attribute value being validated. Defaults to null, meaning using the name of the attribute being validated.

See Also

  • className
className property
public string $className;

the ActiveRecord class name that should be used to look for the attribute value being validated. Defaults to null, meaning using the ActiveRecord class of the attribute being validated. You may use path alias to reference a class name here.

See Also

  • attributeName
criteria property (available since v1.0.8)
public array $criteria;

additional query criteria. This will be combined with the condition that checks if the attribute value exists in the corresponding table column. This array will be used to instantiate a CDbCriteria object.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CFileValidator

Package | system.validators
Inheritance | class CFileValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CFileValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFileValidator verifies if an attribute is receiving a valid uploaded file.

It uses the model class and attribute name to retrieve the information about the uploaded file. It then checks if a file is uploaded successfully, if the file size is within the limit and if the file type is allowed.

This validator will attempt to fetch uploaded data if attribute is not previously set. Please note that this cannot be done if input is tabular:
 foreach($models as $i=>$model)
    $model->attribute = CUploadedFile::getInstance($model, "[$i]attribute");
Please note that you must use {link CUploadedFile::getInstances} for multiple file uploads.

When using CFileValidator with an active record, the following code is often used:
 if($model->save())
 {
    // single upload
    $model->attribute->saveAs($path);
    // multiple upload
    foreach($model->attribute as $file)
       $file->saveAs($path);
 }

You can use CFileValidator to validate the file attribute.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute requires a file to be uploaded or not. | CFileValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
maxFiles | integer | the maximum file count the given attribute can hold. | CFileValidator
maxSize | integer | the maximum number of bytes required for the uploaded file. | CFileValidator
message | string | the user-defined error message. | CValidator
minSize | integer | the minimum number of bytes required for the uploaded file. | CFileValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
tooLarge | string | the error message used when the uploaded file is too large. | CFileValidator
tooMany | string | the error message used if the count of multiple uploads exceeds limit. | CFileValidator
tooSmall | string | the error message used when the uploaded file is too small. | CFileValidator
types | mixed | a list of file name extensions that are allowed to be uploaded. | CFileValidator
wrongType | string | the error message used when the uploaded file has an extension name that is not listed among extensions. | CFileValidator

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
sizeLimit | integer | Returns the maximum size allowed for uploaded files. | CFileValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
emptyAttribute() | Raises an error to inform end user about blank attribute. | CFileValidator
getSizeLimit() | Returns the maximum size allowed for uploaded files. | CFileValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Set the attribute and then validates using validateFile. | CFileValidator
validateFile() | Internally validates a file object. | CFileValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute requires a file to be uploaded or not. Defaults to false, meaning a file is required to be uploaded.

maxFiles property
public integer $maxFiles;

the maximum file count the given attribute can hold. It defaults to 1, meaning single file upload. By defining a higher number, multiple uploads become possible.

maxSize property
public integer $maxSize;

the maximum number of bytes required for the uploaded file. Defaults to null, meaning no limit. Note, the size limit is also affected by 'upload_max_filesize' INI setting and the 'MAX_FILE_SIZE' hidden field value.

See Also

  • tooLarge
minSize property
public integer $minSize;

the minimum number of bytes required for the uploaded file. Defaults to null, meaning no limit.

See Also

  • tooSmall
sizeLimit property read-only
protected integer getSizeLimit()

Returns the maximum size allowed for uploaded files. This is determined based on three factors:

  • 'upload_max_filesize' in php.ini
  • 'MAX_FILE_SIZE' hidden field
  • maxSize

tooLarge property
public string $tooLarge;

the error message used when the uploaded file is too large.

See Also

  • maxSize
tooMany property
public string $tooMany;

the error message used if the count of multiple uploads exceeds limit.

tooSmall property
public string $tooSmall;

the error message used when the uploaded file is too small.

See Also

  • minSize
types property
public mixed $types;

a list of file name extensions that are allowed to be uploaded. This can be either an array or a string consisting of file extension names separated by space or comma (e.g. "gif, jpg"). Extension names are case-insensitive. Defaults to null, meaning all file name extensions are allowed.

wrongType property
public string $wrongType;

the error message used when the uploaded file has an extension name that is not listed among extensions.

Method Details

emptyAttribute() method
protected void emptyAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Raises an error to inform end user about blank attribute.

getSizeLimit() method
protected integer getSizeLimit()
{return} integer the size limit for uploaded files.

Returns the maximum size allowed for uploaded files. This is determined based on three factors:

  • 'upload_max_filesize' in php.ini
  • 'MAX_FILE_SIZE' hidden field
  • maxSize

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Set the attribute and then validates using validateFile. If there is any error, the error message is added to the object.

validateFile() method
protected void validateFile(CModel $object, string $attribute, CUploadedFile $file)
$object | CModel | the object being validated
$attribute | string | the attribute being validated
$file | CUploadedFile | uploaded file passed to check against a set of rules

Internally validates a file object.


CFilterValidator

Package | system.validators
Inheritance | class CFilterValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CFilterValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFilterValidator transforms the data being validated based on a filter.

CFilterValidator is actually not a validator but a data processor. It invokes the specified filter method to process the attribute value and save the processed value back to the attribute. The filter method must follow the following signature:
function foo($value) {...return $newValue; }
Many PHP functions qualify this signature (e.g. trim).

To specify the filter method, set filter property to be the function name.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
filter | callback | the filter method | CFilterValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CFilterValidator

Property Details

filter property
public callback $filter;

the filter method

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CInlineValidator

Package | system.validators
Inheritance | class CInlineValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CInlineValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CInlineValidator represents a validator which is defined as a method in the object being validated.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
method | string | the name of the validation method defined in the active record class | CInlineValidator
on | array | list of scenarios that the validator should be applied. | CValidator
params | array | additional parameters that are passed to the validation method | CInlineValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CInlineValidator

Property Details

method property
public string $method;

the name of the validation method defined in the active record class

params property
public array $params;

additional parameters that are passed to the validation method

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CNumberValidator

Package | system.validators
Inheritance | class CNumberValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CNumberValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CNumberValidator validates that the attribute value is a number.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CNumberValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
integerOnly | boolean | whether the attribute value can only be an integer. | CNumberValidator
max | integer|double | upper limit of the number. | CNumberValidator
message | string | the user-defined error message. | CValidator
min | integer|double | lower limit of the number. | CNumberValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
tooBig | string | user-defined error message used when the value is too big. | CNumberValidator
tooSmall | string | user-defined error message used when the value is too small. | CNumberValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CNumberValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

integerOnly property
public boolean $integerOnly;

whether the attribute value can only be an integer. Defaults to false.

max property
public integer|double $max;

upper limit of the number. Defaults to null, meaning no upper limit.

min property
public integer|double $min;

lower limit of the number. Defaults to null, meaning no lower limit.

tooBig property
public string $tooBig;

user-defined error message used when the value is too big.

tooSmall property
public string $tooSmall;

user-defined error message used when the value is too small.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CRangeValidator

Package | system.validators
Inheritance | class CRangeValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CRangeValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CRangeValidator validates that the attribute value is among the list (specified via range).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CRangeValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
range | array | list of valid values that the attribute value should be among | CRangeValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
strict | boolean | whether the comparison is strict (both type and value must be the same) | CRangeValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CRangeValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

range property
public array $range;

list of valid values that the attribute value should be among

strict property
public boolean $strict;

whether the comparison is strict (both type and value must be the same)

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CRegularExpressionValidator

Package | system.validators
Inheritance | class CRegularExpressionValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CRegularExpressionValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CRegularExpressionValidator validates that the attribute value matches to the specified regular expression.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CRegularExpressionValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
pattern | string | the regular expression to be matched with | CRegularExpressionValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CRegularExpressionValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

pattern property
public string $pattern;

the regular expression to be matched with

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CRequiredValidator

Package | system.validators
Inheritance | class CRequiredValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CRequiredValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CRequiredValidator validates that the specified attribute does not have null or empty value.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
requiredValue | mixed | the desired value that the attribute must have. | CRequiredValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
strict | boolean | whether the comparison to requiredValue is strict. | CRequiredValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CRequiredValidator

Property Details

requiredValue property (available since v1.0.10)
public mixed $requiredValue;

the desired value that the attribute must have. If this is null, the validator will validate that the specified attribute does not have null or empty value. If this is set as a value that is not null, the validator will validate that the attribute has a value that is the same as this property value. Defaults to null.

strict property (available since v1.0.10)
public boolean $strict;

whether the comparison to requiredValue is strict. When this is true, the attribute value and type must both match those of requiredValue. Defaults to false, meaning only the value needs to be matched. This property is only used when requiredValue is not null.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CSafeValidator

Package | system.validators
Inheritance | class CSafeValidator » CValidator » CComponent
Since | 1.1
Version | $Id: CSafeValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSafeValidator marks the associated attributes to be safe for massive assignments.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CSafeValidator

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CStringValidator

Package | system.validators
Inheritance | class CStringValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CStringValidator.php 1882 2010-03-10 22:35:58Z qiang.xue $
CStringValidator validates that the attribute value is of certain length.

Note, this validator should only be used with string-typed attributes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CStringValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
encoding | string | the encoding of the string value to be validated (e. | CStringValidator
is | integer | exact length. | CStringValidator
max | integer | maximum length. | CStringValidator
message | string | the user-defined error message. | CValidator
min | integer | minimum length. | CStringValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
tooLong | string | user-defined error message used when the value is too short. | CStringValidator
tooShort | string | user-defined error message used when the value is too long. | CStringValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CStringValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

encoding property (available since v1.1.1)
public string $encoding;

the encoding of the string value to be validated (e.g. 'UTF-8'). Setting this property requires you to enable mbstring PHP extension. The value of this property will be used as the 2nd parameter of the mb_strlen() function. Defaults to false, which means the strlen() function will be used for calculating the length of the string.

is property
public integer $is;

exact length. Defaults to null, meaning no exact length limit.

max property
public integer $max;

maximum length. Defaults to null, meaning no maximum limit.

min property
public integer $min;

minimum length. Defaults to null, meaning no minimum limit.

tooLong property
public string $tooLong;

user-defined error message used when the value is too short.

tooShort property
public string $tooShort;

user-defined error message used when the value is too long.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CTypeValidator

Package | system.validators
Inheritance | class CTypeValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CTypeValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CTypeValidator verifies if the attribute is of the type specified by type.

The following data types are supported:
  • integer A 32-bit signed integer data type.
  • float A double-precision floating point number data type.
  • string A string data type.
  • date A date data type.
  • time A time data type (available since version 1.0.5).
  • datetime A date and time data type (available since version 1.0.5).

For date type, the property dateFormat will be used to determine how to parse the date string. If the given date value doesn't follow the format, the attribute is considered as invalid.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CTypeValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
dateFormat | string | the format pattern that the date value should follow. | CTypeValidator
datetimeFormat | string | the format pattern that the datetime value should follow. | CTypeValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator
timeFormat | string | the format pattern that the time value should follow. | CTypeValidator
type | string | the data type that the attribute should be. | CTypeValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CTypeValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

dateFormat property
public string $dateFormat;

the format pattern that the date value should follow. Defaults to 'MM/dd/yyyy'. Please see CDateTimeParser for details about how to specify a date format. This property is effective only when type is 'date'.

datetimeFormat property (available since v1.0.5)
public string $datetimeFormat;

the format pattern that the datetime value should follow. Defaults to 'MM/dd/yyyy hh:mm'. Please see CDateTimeParser for details about how to specify a datetime format. This property is effective only when type is 'datetime'.

timeFormat property (available since v1.0.5)
public string $timeFormat;

the format pattern that the time value should follow. Defaults to 'hh:mm'. Please see CDateTimeParser for details about how to specify a time format. This property is effective only when type is 'time'.

type property
public string $type;

the data type that the attribute should be. Defaults to 'string'. Valid values include 'string', 'integer', 'float', 'date', 'time' and 'datetime'. Note that 'time' and 'datetime' have been available since version 1.0.5.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CUniqueValidator

Package | system.validators
Inheritance | class CUniqueValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CUniqueValidator.php 1881 2010-03-10 22:17:34Z qiang.xue $
CUniqueValidator validates that the attribute value is unique in the corresponding database table.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CUniqueValidator
attributeName | string | the ActiveRecord class attribute name that should be used to look for the attribute value being validated. | CUniqueValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
caseSensitive | boolean | whether the comparison is case sensitive. | CUniqueValidator
className | string | the ActiveRecord class name that should be used to look for the attribute value being validated. | CUniqueValidator
criteria | array | additional query criteria. | CUniqueValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CUniqueValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

attributeName property (available since v1.0.8)
public string $attributeName;

the ActiveRecord class attribute name that should be used to look for the attribute value being validated. Defaults to null, meaning using the name of the attribute being validated.

See Also

  • className
caseSensitive property
public boolean $caseSensitive;

whether the comparison is case sensitive. Defaults to true. Note, by setting it to false, you are assuming the attribute type is string.

className property (available since v1.0.8)
public string $className;

the ActiveRecord class name that should be used to look for the attribute value being validated. Defaults to null, meaning using the class of the object currently being validated. You may use path alias to reference a class name here.

See Also

  • attributeName
criteria property (available since v1.0.8)
public array $criteria;

additional query criteria. This will be combined with the condition that checks if the attribute value exists in the corresponding table column. This array will be used to instantiate a CDbCriteria object.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CUnsafeValidator

Package | system.validators
Inheritance | class CUnsafeValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CUnsafeValidator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CUnsafeValidator marks the associated attributes to be unsafe so that they cannot be massively assigned.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CUnsafeValidator

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.


CUrlValidator

Package | system.validators
Inheritance | class CUrlValidator » CValidator » CComponent
Since | 1.0
Version | $Id: CUrlValidator.php 1840 2010-02-26 04:34:30Z qiang.xue $
CUrlValidator validates that the attribute value is a valid http or https URL.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowEmpty | boolean | whether the attribute value can be null or empty. | CUrlValidator
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
pattern | string | the regular expression used to validates the attribute value. | CUrlValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator
validateValue() | Validates a static value to see if it is a valid URL. | CUrlValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates the attribute of the object. | CUrlValidator

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the attribute value can be null or empty. Defaults to true, meaning that if the attribute is empty, it is considered valid.

pattern property
public string $pattern;

the regular expression used to validates the attribute value.

Method Details

validateAttribute() method
protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the object being validated
$attribute | string | the attribute being validated

Validates the attribute of the object. If there is any error, the error message is added to the object.

validateValue() method (available since v1.1.1)
public boolean validateValue(mixed $value)
$value | mixed | the value to be validated
{return} | boolean | whether the value is a valid URL

Validates a static value to see if it is a valid URL. Note that this method does not respect allowEmpty property. This method is provided so that you can call it directly without going through the model validation rule mechanism.


CValidator

Package | system.validators
Inheritance | abstract class CValidator » CComponent
Subclasses | CBooleanValidator, CCaptchaValidator, CCompareValidator, CDefaultValueValidator, CEmailValidator, CExistValidator, CFileValidator, CFilterValidator, CInlineValidator, CNumberValidator, CRangeValidator, CRegularExpressionValidator, CRequiredValidator, CSafeValidator, CStringValidator, CTypeValidator, CUniqueValidator, CUnsafeValidator, CUrlValidator
Since | 1.0
Version | $Id: CValidator.php 1838 2010-02-26 03:52:44Z qiang.xue $
CValidator is the base class for all validators.

Child classes must implement the validateAttribute method.

The following properties are defined in CValidator:
  • attributes: array, list of attributes to be validated;
  • message: string, the customized error message. The message may contain placeholders that will be replaced with the actual content. For example, the "{attribute}" placeholder will be replaced with the label of the problematic attribute. Different validators may define additional placeholders.
  • on: string, in which scenario should the validator be in effect. This is used to match the 'on' parameter supplied when calling CModel::validate.

When using createValidator to create a validator, the following aliases are recognized as the corresponding built-in validator classes:
  • required: CRequiredValidator
  • filter: CFilterValidator
  • match: CRegularExpressionValidator
  • email: CEmailValidator
  • url: CUrlValidator
  • unique: CUniqueValidator
  • compare: CCompareValidator
  • length: CStringValidator
  • in: CRangeValidator
  • numerical: CNumberValidator
  • captcha: CCaptchaValidator
  • type: CTypeValidator
  • file: CFileValidator
  • default: CDefaultValueValidator
  • exist: CExistValidator
  • boolean: CBooleanValidator
  • safe: CSafeValidator
  • unsafe: CUnsafeValidator

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes to be validated. | CValidator
builtInValidators | array | list of built-in validators (name=>class) | CValidator
message | string | the user-defined error message. | CValidator
on | array | list of scenarios that the validator should be applied. | CValidator
skipOnError | boolean | whether this validation rule should be skipped if when there is already a validation error for the current attribute. | CValidator

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyTo() | Returns a value indicating whether the validator applies to the specified scenario. | CValidator
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createValidator() | Creates a validator object. | CValidator
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
validate() | Validates the specified object. | CValidator

Protected Methods

Hide inherited methods

Method | Description | Defined By
addError() | Adds an error about the specified attribute to the active record. | CValidator
isEmpty() | Checks if the given value is empty. | CValidator
validateAttribute() | Validates a single attribute. | CValidator

Property Details

attributes property
public array $attributes;

list of attributes to be validated.

builtInValidators property
public static array $builtInValidators;

list of built-in validators (name=>class)

message property
public string $message;

the user-defined error message. Different validators may define various placeholders in the message that are to be replaced with actual values. All validators recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.

on property
public array $on;

list of scenarios that the validator should be applied. Each array value refers to a scenario name with the same name as its array key.

skipOnError property (available since v1.1.1)
public boolean $skipOnError;

whether this validation rule should be skipped if when there is already a validation error for the current attribute. Defaults to false.

Method Details

addError() method
protected void addError(CModel $object, string $attribute, string $message, array $params=array ( ))
$object | CModel | the data object being validated
$attribute | string | the attribute being validated
$message | string | the error message
$params | array | values for the placeholders in the error message

Adds an error about the specified attribute to the active record. This is a helper method that performs message selection and internationalization.

applyTo() method (available since v1.0.2)
public boolean applyTo(string $scenario)
$scenario | string | scenario name
{return} | boolean | whether the validator applies to the specified scenario.

Returns a value indicating whether the validator applies to the specified scenario. A validator applies to a scenario as long as any of the following conditions is met:

  • the validator's "on" property is empty
  • the validator's "on" property contains the specified scenario

createValidator() method
public static CValidator createValidator(string $name, CModel $object, mixed $attributes, array $params)
$name | string | the name or class of the validator
$object | CModel | the data object being validated that may contain the inline validation method
$attributes | mixed | list of attributes to be validated. This can be either an array of the attribute names or a string of comma-separated attribute names.
$params | array | initial values to be applied to the validator properties
{return} | CValidator | the validator

Creates a validator object.

isEmpty() method (available since v1.0.9)
protected boolean isEmpty(mixed $value, boolean $trim=false)
$value | mixed | the value to be checked
$trim | boolean | whether to perform trimming before checking if the string is empty. Defaults to false.
{return} | boolean | whether the value is empty

Checks if the given value is empty. A value is considered empty if it is null, an empty array, or the trimmed result is an empty string. Note that this method is different from PHP empty(). It will return false when the value is 0.

validate() method
public void validate(CModel $object, array $attributes=NULL)
$object | CModel | the data object being validated
$attributes | array | the list of attributes to be validated. Defaults to null, meaning every attribute listed in attributes will be validated.

Validates the specified object.

validateAttribute() method
abstract protected void validateAttribute(CModel $object, string $attribute)
$object | CModel | the data object being validated
$attribute | string | the name of the attribute to be validated.

Validates a single attribute. This method should be overriden by child classes.


CActiveDataProvider

Package | system.web
Inheritance | class CActiveDataProvider » CDataProvider » CComponent
Implements | IDataProvider
Since | 1.1
Version | $Id: CActiveDataProvider.php 1758 2010-01-28 02:19:39Z qiang.xue $
CActiveDataProvider implements a data provider based on ActiveRecord.

CActiveDataProvider provides data in terms of ActiveRecord objects which are of class modelClass. It uses the AR CActiveRecord::findAll method to retrieve the data from database. The criteria property can be used to specify various query options, such as conditions, sorting, pagination, etc.

CActiveDataProvider may be used in the following way:
$dataProvider=new CActiveDataProvider('Post', array(
    'criteria'=>array(
        'condition'=>'status=1 AND tags LIKE :tags',
        'params'=>array(':tags'=>$_GET['tags']),
        'with'=>array('author'),
    ),
    'pagination'=>array(
        'pageSize'=>20,
    ),
));
// $dataProvider->getData() will return a list of Post objects

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
criteria | CDbCriteria | the query criteria | CActiveDataProvider
data | array | Returns the data items currently available. | CDataProvider
id | string | the unique ID that uniquely identifies the data provider among all data providers. | CDataProvider
itemCount | integer | Returns the number of data items in the current page. | CDataProvider
keyAttribute | string | the name of key attribute for modelClass. | CActiveDataProvider
keys | array | Returns the key values associated with the data items. | CDataProvider
modelClass | string | the primary ActiveRecord class name. | CActiveDataProvider
pagination | CPagination | the pagination object. | CDataProvider
sort | CSort | the sorting object. | CActiveDataProvider
totalItemCount | integer | Returns the total number of data items. | CDataProvider

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CActiveDataProvider
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCriteria() |  | CActiveDataProvider
getData() | Returns the data items currently available. | CDataProvider
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CDataProvider
getItemCount() | Returns the number of data items in the current page. | CDataProvider
getKeys() | Returns the key values associated with the data items. | CDataProvider
getPagination() |  | CDataProvider
getSort() |  | CActiveDataProvider
getTotalItemCount() | Returns the total number of data items. | CDataProvider
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setCriteria() |  | CActiveDataProvider
setData() |  | CDataProvider
setId() |  | CDataProvider
setKeys() |  | CDataProvider
setPagination() |  | CDataProvider
setSort() |  | CDataProvider
setTotalItemCount() | Sets the total number of data items. | CDataProvider

Protected Methods

Hide inherited methods

Method | Description | Defined By
calculateTotalItemCount() | Calculates the total number of data items. | CActiveDataProvider
fetchData() | Fetches the data from the persistent data storage. | CActiveDataProvider
fetchKeys() | Fetches the data item keys from the persistent data storage. | CActiveDataProvider

Property Details

criteria property
public CDbCriteria getCriteria()
public void setCriteria(mixed $value)

the query criteria

keyAttribute property
public string $keyAttribute;

the name of key attribute for modelClass. If not set, it means the primary key of the corresponding database table will be used.

modelClass property
public string $modelClass;

the primary ActiveRecord class name. The getData() method will return a list of objects of this class.

sort property
public CSort getSort()
public void setSort(mixed $value)

the sorting object. If this is false, it means the sorting is disabled.

Method Details

__construct() method
public void __construct(string $modelClass, array $config=array ( ))
$modelClass | string | the model class. This will be assigned to the modelClass property.
$config | array | configuration (name=>value) to be applied to this data provider. Any public properties of the data provider can be configured via this parameter

Constructor.

calculateTotalItemCount() method
protected integer calculateTotalItemCount()
{return} integer the total number of data items.

Calculates the total number of data items.

fetchData() method
protected array fetchData()
{return} array list of data items

Fetches the data from the persistent data storage.

fetchKeys() method
protected array fetchKeys()
{return} array list of data item keys.

Fetches the data item keys from the persistent data storage.

getCriteria() method
public CDbCriteria getCriteria()
{return} CDbCriteria the query criteria

getSort() method
public CSort getSort()
{return} CSort the sorting object. If this is false, it means the sorting is disabled.

setCriteria() method
public void setCriteria(mixed $value)
$value mixed the query criteria. This can be either a CDbCriteria object or an array representing the query criteria.


CAssetManager

Package | system.web
Inheritance | class CAssetManager » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CAssetManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAssetManager is a Web application component that manages private files (called assets) and makes them accessible by Web clients.

It achieves this goal by copying assets to a Web-accessible directory and returns the corresponding URL for accessing them.

To publish an asset, simply call publish().

The Web-accessible directory holding the published files is specified by basePath, which defaults to the "assets" directory under the directory containing the application entry script file. The property baseUrl refers to the URL for accessing the basePath.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the root directory storing the published asset files | CAssetManager
baseUrl | string | the base url that the published asset files can be accessed. | CAssetManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBasePath() |  | CAssetManager
getBaseUrl() |  | CAssetManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getPublishedPath() | Returns the published path of a file path. | CAssetManager
getPublishedUrl() | Returns the URL of a published file path. | CAssetManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CAssetManager
publish() | Publishes a file or a directory. | CAssetManager
raiseEvent() | Raises an event. | CComponent
setBasePath() | Sets the root directory storing published asset files. | CAssetManager
setBaseUrl() |  | CAssetManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
hash() | Generate a CRC32 hash for the directory path. Collisions are higher | CAssetManager

Property Details

basePath property
public string getBasePath()
public void setBasePath(string $value)

the root directory storing the published asset files

baseUrl property
public string getBaseUrl()
public void setBaseUrl(string $value)

the base url that the published asset files can be accessed. Note, the ending slashes are stripped off.

Method Details

getBasePath() method
public string getBasePath()
{return} string the root directory storing the published asset files

getBaseUrl() method
public string getBaseUrl()
{return} string the base url that the published asset files can be accessed. Note, the ending slashes are stripped off.

getPublishedPath() method
public string getPublishedPath(string $path, boolean $hashByName=false)
$path | string | directory or file path being published
$hashByName | boolean | whether the published directory should be named as the hashed basename. If false, the name will be the hashed dirname of the path being published. Defaults to false. Set true if the path being published is shared among different extensions.
{return} | string | the published file path. False if the file or directory does not exist

Returns the published path of a file path. This method does not perform any publishing. It merely tells you if the file or directory is published, where it will go.

getPublishedUrl() method
public string getPublishedUrl(string $path, boolean $hashByName=false)
$path | string | directory or file path being published
$hashByName | boolean | whether the published directory should be named as the hashed basename. If false, the name will be the hashed dirname of the path being published. Defaults to false. Set true if the path being published is shared among different extensions.
{return} | string | the published URL for the file or directory. False if the file or directory does not exist.

Returns the URL of a published file path. This method does not perform any publishing. It merely tells you if the file path is published, what the URL will be to access it.

hash() method
protected string hash(string $path)
$path | string | string to be hashed.
{return} | string | hashed string.

Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string.

init() method
public void init()

Initializes the application component. This method is required by IApplicationComponent and is invoked by application.

publish() method
public string publish(string $path, boolean $hashByName=false, integer $level=-1)
$path | string | the asset (file or directory) to be published
$hashByName | boolean | whether the published directory should be named as the hashed basename. If false, the name will be the hashed dirname of the path being published. Defaults to false. Set true if the path being published is shared among different extensions.
$level | integer | level of recursive copying when the asset is a directory. Level -1 means publishing all subdirectories and files; Level 0 means publishing only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.
{return} | string | an absolute URL to the published asset

Publishes a file or a directory. This method will copy the specified asset to a web accessible directory and return the URL for accessing the published asset.

  • If the asset is a file, its file modification time will be checked to avoid unnecessary file copying;
  • If the asset is a directory, all files and subdirectories under it will be published recursively. Note, in this case the method only checks the existence of the target directory to avoid repetitive copying.

setBasePath() method
public void setBasePath(string $value)
$value string the root directory storing published asset files

Sets the root directory storing published asset files.

setBaseUrl() method
public void setBaseUrl(string $value)
$value string the base url that the published asset files can be accessed


CBaseController

All Packages | Methods
Package | system.web
Inheritance | abstract class CBaseController » CComponent
Subclasses | CController, CWidget
Since | 1.0
Version | $Id: CBaseController.php 1678 2010-01-07 21:02:00Z qiang.xue $
CBaseController is the base class for CController and CWidget.

It provides the common functionalities shared by controllers who need to render views.

CBaseController also implements the support for the following features:
  • Clips : a clip is a piece of captured output that can be inserted elsewhere.
  • Widgets : a widget is a self-contained sub-controller with its own view and model.
  • Fragment cache : fragment cache selectively caches a portion of the output.

To use a widget in a view, use the following in the view:
$this->widget('path.to.widgetClass',array('property1'=>'value1',...));
or
$this->beginWidget('path.to.widgetClass',array('property1'=>'value1',...));
// ... display other contents here
$this->endWidget();

To create a clip, use the following:
$this->beginClip('clipID');
// ... display the clip contents
$this->endClip();
Then, in a different view or place, the captured clip can be inserted as:
echo $this->clips['clipID'];

To use fragment cache, do as follows,
if($this->beginCache('cacheID',array('property1'=>'value1',...))
{
    // ... display the content to be cached here
   $this->endCache();
}

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getViewFile() | Returns the view script file according to the specified view name. | CBaseController
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
widget() | Creates a widget and executes it. | CBaseController

Method Details

beginCache() method
public boolean beginCache(string $id, array $properties=array ( ))
$id | string | a unique ID identifying the fragment to be cached.
$properties | array | initial property values for COutputCache.
{return} | boolean | whether we need to generate content for caching. False if cached version is available.

Begins fragment caching. This method will display cached content if it is availabe. If not, it will start caching and would expect a endCache() call to end the cache and save the content into cache. A typical usage of fragment caching is as follows,

if($this->beginCache($id))
{
    // ...generate content here
    $this->endCache();
}

See Also

  • endCache
beginClip() method
public void beginClip(string $id, array $properties=array ( ))
$id | string | the clip ID.
$properties | array | initial property values for CClipWidget.

Begins recording a clip. This method is a shortcut to beginning CClipWidget.

beginContent() method
public void beginContent(mixed $view=NULL, array $data=array ( ))
$view | mixed | the name of the view that will be used to decorate the content. The actual view script is resolved via getViewFile. If this parameter is null (default), the default layout will be used as the decorative view. Note that if the current controller does not belong to any module, the default layout refers to the application's default layout; If the controller belongs to a module, the default layout refers to the module's default layout.
$data | array | the variables (name=>value) to be extracted and made available in the decorative view. This parameter has been available since version 1.0.4

Begins the rendering of content that is to be decorated by the specified view.

See Also

  • beginContent
  • CContentDecorator
beginWidget() method
public CWidget beginWidget(string $className, array $properties=array ( ))
$className | string | the widget class name or class in dot syntax (e.g. application.widgets.MyWidget)
$properties | array | list of initial property values for the widget (Property Name => Property Value)
{return} | CWidget | the widget created to run

Creates a widget and executes it. This method is similar to widget() except that it is expecting a endWidget() call to end the execution.

See Also

  • endWidget
createWidget() method
public CWidget createWidget(string $className, array $properties=array ( ))
$className | string | class name (can be in path alias format)
$properties | array | initial property values
{return} | CWidget | the fully initialized widget instance.

Creates a widget and initializes it. This method first creates the specified widget instance. It then configures the widget's properties with the given initial values. At the end it calls CWidget::init to initialize the widget. Starting from version 1.1, if a widget factory is enabled, this method will use the factory to create the widget, instead.

endCache() method
public void endCache()

Ends fragment caching. This is an alias to endWidget.

See Also

  • beginCache
endClip() method
public void endClip()

Ends recording a clip. This method is an alias to endWidget.

endContent() method
public void endContent()

Ends the rendering of content.

See Also

  • beginContent
endWidget() method
public CWidget endWidget(string $id='')
$id | string | optional tag identifying the method call for debugging purpose.
{return} | CWidget | the widget just ended running

Ends the execution of the named widget. This method is used together with beginWidget().

See Also

  • beginWidget
getViewFile() method
abstract public string getViewFile(string $viewName)
$viewName | string | view name
{return} | string | the file path for the named view. False if the view cannot be found.

Returns the view script file according to the specified view name. This method must be implemented by child classes.

renderFile() method
public string renderFile(string $viewFile, array $data=NULL, boolean $return=false)
$viewFile | string | view file path
$data | array | data to be extracted and made available to the view
$return | boolean | whether the rendering result should be returned instead of being echoed
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a view file.

renderInternal() method
public string renderInternal(string $_viewFile_, array $_data_=NULL, boolean $_return_=false)
$_viewFile_ | string | view file
$_data_ | array | data to be extracted and made available to the view file
$_return_ | boolean | whether the rendering result should be returned as a string
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a view file. This method includes the view file as a PHP script and captures the display result if required.

widget() method
public CWidget widget(string $className, array $properties=array ( ))
$className | string | the widget class name or class in dot syntax (e.g. application.widgets.MyWidget)
$properties | array | list of initial property values for the widget (Property Name => Property Value)
{return} | CWidget | the widget instance. This return value has been available since version 1.0.4.

Creates a widget and executes it.


CCacheHttpSession

Package | system.web
Inheritance | class CCacheHttpSession » CHttpSession » CApplicationComponent » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate, IApplicationComponent
Since | 1.0
Version | $Id: CCacheHttpSession.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCacheHttpSession implements a session component using cache as storage medium.

The cache being used can be any cache application component implementing ICache interface. The ID of the cache application component is specified via cacheID, which defaults to 'cache'.

Beware, by definition cache storage are volatile, which means the data stored on them may be swapped out and get lost. Therefore, you must make sure the cache used by this component is NOT volatile. If you want to use CDbCache as storage medium, use CDbHttpSession is a better choice.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoStart | boolean | whether the session should be automatically started when the session application component is initialized, defaults to true. | CHttpSession
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component. | CCacheHttpSession
cookieMode | string | how to use cookie to store session ID. | CHttpSession
cookieParams | array | the session cookie parameters. | CHttpSession
count | integer | the number of session variables | CHttpSession
gCProbability | integer | the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. | CHttpSession
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
isStarted | boolean | whether the session has started | CHttpSession
iterator | CHttpSessionIterator | Returns an iterator for traversing the session variables. | CHttpSession
keys | array | the list of session variable names | CHttpSession
savePath | string | the current session save path, defaults to '/tmp'. | CHttpSession
sessionID | string | the current session ID | CHttpSession
sessionName | string | the current session name | CHttpSession
timeout | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. | CHttpSession
useCustomStorage | boolean | Returns a value indicating whether to use custom session storage. | CCacheHttpSession
useTransparentSessionID | boolean | whether transparent sid support is enabled or not, defaults to false. | CHttpSession

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds a session variable. | CHttpSession
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all session variables | CHttpSession
close() | Ends the current session and store session data. | CHttpSession
closeSession() | Session close handler. | CHttpSession
contains() |  | CHttpSession
count() | Returns the number of items in the session. | CHttpSession
destroy() | Frees all session variables and destroys all data registered to a session. | CHttpSession
destroySession() | Session destroy handler. | CCacheHttpSession
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
gcSession() | Session GC (garbage collection) handler. | CHttpSession
getCookieMode() |  | CHttpSession
getCookieParams() |  | CHttpSession
getCount() |  | CHttpSession
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getGCProbability() |  | CHttpSession
getIsInitialized() |  | CApplicationComponent
getIsStarted() |  | CHttpSession
getIterator() | Returns an iterator for traversing the session variables. | CHttpSession
getKeys() |  | CHttpSession
getSavePath() |  | CHttpSession
getSessionID() |  | CHttpSession
getSessionName() |  | CHttpSession
getTimeout() |  | CHttpSession
getUseCustomStorage() | Returns a value indicating whether to use custom session storage. | CCacheHttpSession
getUseTransparentSessionID() |  | CHttpSession
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CCacheHttpSession
itemAt() | Returns the session variable value with the session variable name. | CHttpSession
offsetExists() | This method is required by the interface ArrayAccess. | CHttpSession
offsetGet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetSet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetUnset() | This method is required by the interface ArrayAccess. | CHttpSession
open() | Starts the session if it has not started yet. | CHttpSession
openSession() | Session open handler. | CHttpSession
raiseEvent() | Raises an event. | CComponent
readSession() | Session read handler. | CCacheHttpSession
remove() | Removes a session variable. | CHttpSession
setCookieMode() |  | CHttpSession
setCookieParams() | Sets the session cookie parameters. | CHttpSession
setGCProbability() |  | CHttpSession
setSavePath() |  | CHttpSession
setSessionID() |  | CHttpSession
setSessionName() |  | CHttpSession
setTimeout() |  | CHttpSession
setUseTransparentSessionID() |  | CHttpSession
toArray() |  | CHttpSession
writeSession() | Session write handler. | CCacheHttpSession

Protected Methods

Hide inherited methods

Method | Description | Defined By
calculateKey() | Generates a unique key used for storing session data in cache. | CCacheHttpSession

Property Details

cacheID property
public string $cacheID;

the ID of the cache application component. Defaults to 'cache' (the primary cache application component.)

useCustomStorage property read-only
public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

Method Details

calculateKey() method
protected string calculateKey(string $id)
$id | string | session variable name
{return} | string | a safe cache key associated with the session variable name

Generates a unique key used for storing session data in cache.

destroySession() method
public boolean destroySession(string $id)
$id | string | session ID
{return} | boolean | whether session is destroyed successfully

Session destroy handler. Do not call this method directly.

getUseCustomStorage() method
public boolean getUseCustomStorage()
{return} boolean whether to use custom storage.

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by checking if cache is available.

readSession() method
public string readSession(string $id)
$id | string | session ID
{return} | string | the session data

Session read handler. Do not call this method directly.

writeSession() method
public boolean writeSession(string $id, string $data)
$id | string | session ID
$data | string | session data
{return} | boolean | whether session write is successful

Session write handler. Do not call this method directly.


CClientScript

Package | system.web
Inheritance | class CClientScript » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CClientScript.php 1863 2010-03-07 13:26:05Z qiang.xue $
CClientScript manages JavaScript and CSS stylesheets for views.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
coreScriptUrl | string | Returns the base URL of all core javascript files. | CClientScript
enableJavaScript | boolean | whether JavaScript should be enabled. | CClientScript
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
scriptMap | array | the mapping between script file names and the corresponding script URLs. | CClientScript

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
cssFiles | array | the registered CSS files (CSS URL=>media type). | CClientScript
scriptFiles | array | the registered JavaScript files (position, key => URL) | CClientScript
scripts | array | the registered JavaScript code blocks (position, key => code) | CClientScript

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCoreScriptUrl() | Returns the base URL of all core javascript files. | CClientScript
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
isCssFileRegistered() | Checks whether the CSS file has been registered. | CClientScript
isCssRegistered() | Checks whether the CSS code has been registered. | CClientScript
isScriptFileRegistered() | Checks whether the JavaScript file has been registered. | CClientScript
isScriptRegistered() | Checks whether the JavaScript code has been registered. | CClientScript
raiseEvent() | Raises an event. | CComponent
registerCoreScript() | Registers a core javascript library. | CClientScript
registerCss() | Registers a piece of CSS code. | CClientScript
registerCssFile() | Registers a CSS file | CClientScript
registerLinkTag() | Registers a link tag that will be inserted in the head section (right before the title element) of the resulting page. | CClientScript
registerMetaTag() | Registers a meta tag that will be inserted in the head section (right before the title element) of the resulting page. | CClientScript
registerScript() | Registers a piece of javascript code. | CClientScript
registerScriptFile() | Registers a javascript file. | CClientScript
render() | Renders the registered scripts. | CClientScript
renderBodyBegin() | Inserts the scripts at the beginning of the body section. | CClientScript
renderBodyEnd() | Inserts the scripts at the end of the body section. | CClientScript
renderCoreScripts() | Renders the specified core javascript library. | CClientScript
renderHead() | Inserts the scripts in the head section. | CClientScript
reset() | Cleans all registered scripts. | CClientScript
setCoreScriptUrl() | Sets the base URL of all core javascript files. | CClientScript

Protected Methods

Hide inherited methods

Method | Description | Defined By
recordCachingAction() | Records a method call when an output cache is in effect. | CClientScript
remapScripts() | Uses scriptMap to re-map the registered scripts. | CClientScript

Property Details

coreScriptUrl property
public string getCoreScriptUrl()
public void setCoreScriptUrl(string $value)

Returns the base URL of all core javascript files. If the base URL is not explicitly set, this method will publish the whole directory 'framework/web/js/source' and return the corresponding URL.

cssFiles property (available since v1.0.4)
protected array $cssFiles;

the registered CSS files (CSS URL=>media type).

enableJavaScript property
public boolean $enableJavaScript;

whether JavaScript should be enabled. Defaults to true.

scriptFiles property (available since v1.0.4)
protected array $scriptFiles;

the registered JavaScript files (position, key => URL)

scriptMap property (available since v1.0.3)
public array $scriptMap;

the mapping between script file names and the corresponding script URLs. The array keys are script file names (without directory part) and the array values are the corresponding URLs. If an array value is false, the corresponding script file will not be rendered. If an array key is '*.js' or '*.css', the corresponding URL will replace all all JavaScript files or CSS files, respectively.

This property is mainly used to optimize the generated HTML pages by merging different scripts files into fewer and optimized script files.

scripts property (available since v1.0.5)
protected array $scripts;

the registered JavaScript code blocks (position, key => code)

Method Details

getCoreScriptUrl() method
public string getCoreScriptUrl()
{return} string the base URL of all core javascript files

Returns the base URL of all core javascript files. If the base URL is not explicitly set, this method will publish the whole directory 'framework/web/js/source' and return the corresponding URL.

isCssFileRegistered() method
public boolean isCssFileRegistered(string $url)
$url | string | URL of the CSS file
{return} | boolean | whether the CSS file is already registered

Checks whether the CSS file has been registered.

isCssRegistered() method
public boolean isCssRegistered(string $id)
$id | string | ID that uniquely identifies the CSS code
{return} | boolean | whether the CSS code is already registered

Checks whether the CSS code has been registered.

isScriptFileRegistered() method
public boolean isScriptFileRegistered(string $url, integer $position=0)
$url | string | URL of the javascript file
$position integer the position of the JavaScript code. Valid values include the following:
  • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
  • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
  • CClientScript::POS_END : the script is inserted at the end of the body section.
{return} | boolean | whether the javascript file is already registered

Checks whether the JavaScript file has been registered.

isScriptRegistered() method
public boolean isScriptRegistered(string $id, integer $position=4)
$id | string | ID that uniquely identifies the JavaScript code
$position integer the position of the JavaScript code. Valid values include the following:
  • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
  • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
  • CClientScript::POS_END : the script is inserted at the end of the body section.
  • CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
  • CClientScript::POS_READY : the script is inserted in the jQuery's ready function.
{return} | boolean | whether the javascript code is already registered

Checks whether the JavaScript code has been registered.

recordCachingAction() method (available since v1.0.5)
protected void recordCachingAction(string $context, string $method, array $params)
$context | string | a property name of the controller. It refers to an object whose method is being called. If empty it means the controller itself.
$method | string | the method name
$params | array | parameters passed to the method

Records a method call when an output cache is in effect. This is a shortcut to Yii::app()->controller->recordCachingAction. In case when controller is absent, nothing is recorded.

See Also

  • COutputCache
registerCoreScript() method
public void registerCoreScript(string $name)
$name string the core javascript library name

Registers a core javascript library.

See Also

  • renderCoreScript
registerCss() method
public void registerCss(string $id, string $css, string $media='')
$id | string | ID that uniquely identifies this piece of CSS code
$css | string | the CSS code
$media | string | media that the CSS code should be applied to. If empty, it means all media types.

Registers a piece of CSS code.

registerCssFile() method
public void registerCssFile(string $url, string $media='')
$url | string | URL of the CSS file
$media | string | media that the CSS file should be applied to. If empty, it means all media types.

Registers a CSS file

registerLinkTag() method (available since v1.0.1)
public void registerLinkTag(string $relation=NULL, string $type=NULL, string $href=NULL, string $media=NULL, array $options=array ( ))
$relation | string | rel attribute of the link tag. If null, the attribute will not be generated.
$type | string | type attribute of the link tag. If null, the attribute will not be generated.
$href | string | href attribute of the link tag. If null, the attribute will not be generated.
$media | string | media attribute of the link tag. If null, the attribute will not be generated.
$options | array | other options in name-value pairs

Registers a link tag that will be inserted in the head section (right before the title element) of the resulting page.

registerMetaTag() method (available since v1.0.1)
public void registerMetaTag(string $content, string $name=NULL, string $httpEquiv=NULL, array $options=array ( ))
$content | string | content attribute of the meta tag
$name | string | name attribute of the meta tag. If null, the attribute will not be generated
$httpEquiv | string | http-equiv attribute of the meta tag. If null, the attribute will not be generated
$options | array | other options in name-value pairs (e.g. 'scheme', 'lang')

Registers a meta tag that will be inserted in the head section (right before the title element) of the resulting page.

registerScript() method
public void registerScript(string $id, string $script, integer $position=4)
$id | string | ID that uniquely identifies this piece of JavaScript code
$script | string | the javascript code
$position integer the position of the JavaScript code. Valid values include the following:
  • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
  • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
  • CClientScript::POS_END : the script is inserted at the end of the body section.
  • CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
  • CClientScript::POS_READY : the script is inserted in the jQuery's ready function.

Registers a piece of javascript code.

registerScriptFile() method
public void registerScriptFile(string $url, integer $position=0)
$url string URL of the javascript file
$position integer the position of the JavaScript code. Valid values include the following:
  • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
  • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
  • CClientScript::POS_END : the script is inserted at the end of the body section.

Registers a javascript file.

remapScripts() method (available since v1.0.3)
protected void remapScripts()

Uses scriptMap to re-map the registered scripts.

render() method
public void render(string $output)
$output string the existing output that needs to be inserted with script tags

Renders the registered scripts. This method is called in CController::render when it finishes rendering content. CClientScript thus gets a chance to insert script tags at head and body sections in the HTML output.

renderBodyBegin() method
public void renderBodyBegin(string $output)
$output string the output to be inserted with scripts.

Inserts the scripts at the beginning of the body section.

renderBodyEnd() method
public void renderBodyEnd(string $output)
$output string the output to be inserted with scripts.

Inserts the scripts at the end of the body section.

renderCoreScripts() method (available since v1.0.3)
public void renderCoreScripts()

Renders the specified core javascript library.

renderHead() method
public void renderHead(string $output)
$output string the output to be inserted with scripts.

Inserts the scripts in the head section.

reset() method
public void reset()

Cleans all registered scripts.

setCoreScriptUrl() method
public void setCoreScriptUrl(string $value)
$value string the base URL of all core javascript files.

Sets the base URL of all core javascript files. This setter is provided in case when core javascript files are manually published to a pre-specified location. This may save asset publishing time for large-scale applications.


CController

Package | system.web
Inheritance | class CController » CBaseController » CComponent
Subclasses | CExtController
Since | 1.0
Version | $Id: CController.php 1852 2010-03-02 20:38:47Z qiang.xue $
CController manages a set of actions which deal with the corresponding user requests.

Through the actions, CController coordinates the data flow between models and views.

When a user requests an action 'XYZ', CController will do one of the following: 1. Method-based action: call method 'actionXYZ' if it exists; 2. Class-based action: create an instance of class 'XYZ' if the class is found in the action class map (specified via actions(), and execute the action; 3. Call missingAction(), which by default will raise a 404 HTTP exception.

If the user does not specify an action, CController will run the action specified by defaultAction, instead.

CController may be configured to execute filters before and after running actions. Filters preprocess/postprocess the user request/response and may quit executing actions if needed. They are executed in the order they are specified. If during the execution, any of the filters returns true, the rest filters and the action will no longer get executed.

Filters can be individual objects, or methods defined in the controller class. They are specified by overriding filters() method. The following is an example of the filter specification:
array(
    'accessControl - login',
    'ajaxOnly + search',
    array(
        'COutputCache + list',
        'duration'=>300,
    ),
)
The above example declares three filters: accessControl, ajaxOnly, COutputCache. The first two are method-based filters (defined in CController), which refer to filtering methods in the controller class; while the last refers to a object-based filter whose class is 'system.web.widgets.COutputCache' and the 'duration' property is initialized as 300 (s).

For method-based filters, a method named 'filterXYZ($filterChain)' in the controller class will be executed, where 'XYZ' stands for the filter name as specified in filters(). Note, inside the filter method, you must call $filterChain->run() if the action should be executed. Otherwise, the filtering process would stop at this filter.

Filters can be specified so that they are executed only when running certain actions. For method-based filters, this is done by using '+' and '-' operators in the filter specification. The '+' operator means the filter runs only when the specified actions are requested; while the '-' operator means the filter runs only when the requested action is not among those actions. For object-based filters, the '+' and '-' operators are following the class name.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
action | CAction | the action currently being executed, null if no active action. | CController
cachingStack | CStack | stack of COutputCache objects | CController
clips | CMap | Returns the list of clips. | CController
defaultAction | string | the name of the default action. | CController
id | string | ID of the controller | CController
layout | mixed | the name of the layout to be applied to this controller's views. | CController
module | CWebModule | the module that this controller belongs to. | CController
pageTitle | string | the page title. | CController
route | string | the route (module ID, controller ID and action ID) of the current request. | CController
uniqueId | string | the controller ID that is prefixed with the module ID (if any). | CController
viewPath | string | Returns the directory containing view files for this controller. | CController

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CController
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
accessRules() | Returns the access rules for this controller. | CController
actions() | Returns a list of external action classes. | CController
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
behaviors() | Returns a list of behaviors that this controller should behave as. | CController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearPageStates() | Removes all page states. | CController
createAbsoluteUrl() | Creates an absolute URL for the specified action defined in this controller. | CController
createAction() | Creates the action instance based on the action name. | CController
createUrl() | Creates a relative URL for the specified action defined in this controller. | CController
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filterAccessControl() | The filter method for 'accessControl' filter. | CController
filterAjaxOnly() | The filter method for 'ajaxOnly' filter. | CController
filterPostOnly() | The filter method for 'postOnly' filter. | CController
filters() | Returns the filter configurations. | CController
forward() | Processes the request using another controller action. | CController
getAction() |  | CController
getCachingStack() |  | CController
getClips() | Returns the list of clips. | CController
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CController
getLayoutFile() | Looks for the view script file for a layout. | CController
getModule() |  | CController
getPageState() | Returns a persistent page state value. | CController
getPageTitle() |  | CController
getRoute() |  | CController
getUniqueId() |  | CController
getViewFile() | Looks for the view file according to the given view name. | CController
getViewPath() | Returns the directory containing view files for this controller. | CController
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the controller. | CController
isCachingStackEmpty() |  | CController
missingAction() | Handles the request whose action is not recognized. | CController
paginate() | Generates pagination information. | CController
processDynamicOutput() | Postprocesses the dynamic output. | CController
processOutput() | Postprocesses the output generated by render(). | CController
raiseEvent() | Raises an event. | CComponent
recordCachingAction() | Records a method call when an output cache is in effect. | CController
redirect() | Redirects the browser to the specified URL or route (controller/action). | CController
refresh() | Refreshes the current page. | CController
render() | Renders a view with a layout. | CController
renderDynamic() | Renders dynamic content returned by the specified callback. | CController
renderDynamicInternal() | This method is internally used. | CController
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
renderPartial() | Renders a view. | CController
renderText() | Renders a static text string. | CController
resolveViewFile() | Finds a view file based on its name. | CController
run() | Runs the named action. | CController
runAction() | Runs the action after passing through all filters. | CController
runActionWithFilters() | Runs an action with the specified filters. | CController
setAction() |  | CController
setPageState() | Saves a persistent page state value. | CController
setPageTitle() |  | CController
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
afterAction() | This method is invoked right after an action is executed. | CController
beforeAction() | This method is invoked right before an action is to be executed (after all possible filters.) | CController
createActionFromMap() | Creates the action instance based on the action map. | CController
loadPageStates() | Loads page states from a hidden input. | CController
replaceDynamicOutput() | Replaces the dynamic content placeholders with actual content. | CController
savePageStates() | Saves page states as a base64 string. | CController

Property Details

action property
public CAction getAction()
public void setAction(CAction $value)

the action currently being executed, null if no active action.

cachingStack property read-only
public CStack getCachingStack(boolean $createIfNull=true)

stack of COutputCache objects

clips property read-only
public CMap getClips()

Returns the list of clips. A clip is a named piece of rendering result that can be inserted at different places.

See Also

  • CClipWidget
defaultAction property
public string $defaultAction;

the name of the default action. Defaults to 'index'.

id property read-only
public string getId()

ID of the controller

layout property
public mixed $layout;

the name of the layout to be applied to this controller's views. Defaults to null, meaning the application layout is used. If it is false, no layout will be applied. Since version 1.0.3, the module layout will be used if the controller belongs to a module and this layout property is null.

module property read-only (available since v1.0.3)
public CWebModule getModule()

the module that this controller belongs to. It returns null if the controller does not belong to any module

pageTitle property
public string getPageTitle()
public void setPageTitle(string $value)

the page title. Defaults to the controller name and the action name.

route property read-only (available since v1.1.0)
public string getRoute()

the route (module ID, controller ID and action ID) of the current request.

uniqueId property read-only (available since v1.0.3)
public string getUniqueId()

the controller ID that is prefixed with the module ID (if any).

viewPath property read-only
public string getViewPath()

Returns the directory containing view files for this controller. The default implementation returns 'protected/views/ControllerID'. Child classes may override this method to use customized view path. If the controller belongs to a module (since version 1.0.3), the default view path is the module view path appended with the controller ID.

Method Details

__construct() method
public void __construct(string $id, CWebModule $module=NULL)
$id | string | id of this controller
$module | CWebModule | the module that this controller belongs to. This parameter has been available since version 1.0.3.

accessRules() method
public array accessRules()
{return} array list of access rules. See CAccessControlFilter for details about rule specification.

Returns the access rules for this controller. Override this method if you use the accessControl filter.

actions() method
public array actions()
{return} array list of external action classes

Returns a list of external action classes. Array keys are action IDs, and array values are the corresponding action class in dot syntax (e.g. 'edit'=>'application.controllers.article.EditArticle') or arrays representing the configuration of the actions, such as the following,

return array(
    'action1'=>'path.to.Action1Class',
    'action2'=>array(
        'class'=>'path.to.Action2Class',
        'property1'=>'value1',
        'property2'=>'value2',
    ),
);
Derived classes may override this method to declare external actions.

Note, in order to inherit actions defined in the parent class, a child class needs to merge the parent actions with child actions using functions like array_merge().

Since version 1.0.1, you may import actions from an action provider (such as a widget, see CWidget::actions), like the following:
return array(
    ...other actions...
    // import actions declared in ProviderClass::actions()
    // the action IDs will be prefixed with 'pro.'
    'pro.'=>'path.to.ProviderClass',
    // similar as above except that the imported actions are
    // configured with the specified initial property values
    'pro2.'=>array(
        'class'=>'path.to.ProviderClass',
        'action1'=>array(
            'property1'=>'value1',
        ),
        'action2'=>array(
            'property2'=>'value2',
        ),
    ),
)

In the above, we differentiate action providers from other action declarations by the array keys. For action providers, the array keys must contain a dot. As a result, an action ID 'pro2.action1' will be resolved as the 'action1' action declared in the 'ProviderClass'.

See Also

  • createAction
afterAction() method
protected void afterAction(CAction $action)
$action CAction the action just executed.

This method is invoked right after an action is executed. You may override this method to do some postprocessing for the action.

beforeAction() method
protected boolean beforeAction(CAction $action)
$action | CAction | the action to be executed.
{return} | boolean | whether the action should be executed.

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.

behaviors() method (available since v1.0.6)
public array behaviors()
{return} array the behavior configurations (behavior name=>behavior configuration)

Returns a list of behaviors that this controller should behave as. The return value should be an array of behavior configurations indexed by behavior names. Each behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName'=>array(
    'class'=>'path.to.BehaviorClass',
    'property1'=>'value1',
    'property2'=>'value2',
)

Note, the behavior classes must implement IBehavior or extend from CBehavior. Behaviors declared in this method will be attached to the controller when it is instantiated.

For more details about behaviors, see CComponent.

clearPageStates() method
public void clearPageStates()

Removes all page states.

createAbsoluteUrl() method
public string createAbsoluteUrl(string $route, array $params=array ( ), string $schema='', string $ampersand='&')
$route | string | the URL route. This should be in the format of 'ControllerID/ActionID'. If the ControllerPath is not present, the current controller ID will be prefixed to the route. If the route is empty, it is assumed to be the current action.
$params | array | additional GET parameters (name=>value). Both the name and value will be URL-encoded.
$schema | string | schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Creates an absolute URL for the specified action defined in this controller.

createAction() method
public CAction createAction(string $actionID)
$actionID | string | ID of the action. If empty, the default action will be used.
{return} | CAction | the action instance, null if the action does not exist.

Creates the action instance based on the action name. The action can be either an inline action or an object. The latter is created by looking up the action map specified in actions.

See Also

  • actions
createActionFromMap() method (available since v1.0.1)
protected CAction createActionFromMap(array $actionMap, string $actionID, string $requestActionID, array $config=array ( ))
$actionMap | array | the action map
$actionID | string | the action ID that has its prefix stripped off
$requestActionID | string | the originally requested action ID
$config | array | the action configuration that should be applied on top of the configuration specified in the map
{return} | CAction | the action instance, null if the action does not exist.

Creates the action instance based on the action map. This method will check to see if the action ID appears in the given action map. If so, the corresponding configuration will be used to create the action instance.

createUrl() method
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$route | string | the URL route. This should be in the format of 'ControllerID/ActionID'. If the ControllerID is not present, the current controller ID will be prefixed to the route. If the route is empty, it is assumed to be the current action. Since version 1.0.3, if the controller belongs to a module, the module ID will be prefixed to the route. (If you do not want the module ID prefix, the route should start with a slash '/'.)
$params | array | additional GET parameters (name=>value). Both the name and value will be URL-encoded. If the name is '#', the corresponding value will be treated as an anchor and will be appended at the end of the URL. This anchor feature has been available since version 1.0.1.
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Creates a relative URL for the specified action defined in this controller.

filterAccessControl() method
public void filterAccessControl(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

The filter method for 'accessControl' filter. This filter is a wrapper of CAccessControlFilter. To use this filter, you must override accessRules method.

filterAjaxOnly() method
public void filterAjaxOnly(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

The filter method for 'ajaxOnly' filter. This filter reports an error if the applied action is receiving a non-AJAX request.

filterPostOnly() method
public void filterPostOnly(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

The filter method for 'postOnly' filter. This filter reports an error if the applied action is receiving a non-POST request.

filters() method
public array filters()
{return} array a list of filter configurations.

Returns the filter configurations.

By overriding this method, child classes can specify filters to be applied to actions.

This method returns an array of filter specifications. Each array element specify a single filter.

For a method-based filter (called inline filter), it is specified as 'FilterName[ +|- Action1, Action2, ...]', where the '+' ('-') operators describe which actions should be (should not be) applied with the filter.

For a class-based filter, it is specified as an array like the following:

array(
    'FilterClass[ +|- Action1, Action2, ...]',
    'name1'=>'value1',
    'name2'=>'value2',
    ...
)
where the name-value pairs will be used to initialize the properties of the filter.

Note, in order to inherit filters defined in the parent class, a child class needs to merge the parent filters with child filters using functions like array_merge().

See Also

  • CFilter
forward() method (available since v1.1.0)
public void forward(string $route, boolean $exit=true)
$route | string | the route of the new controller action. This can be an action ID, or a complete route with module ID (optional in the current module), controller ID and action ID. If the former, the action is assumed to be located within the current controller.
$exit | boolean | whether to end the application after this call. Defaults to true.

Processes the request using another controller action. This is like redirect, but the user browser's URL remains unchanged. In most cases, you should call redirect instead of this method.

getAction() method
public CAction getAction()
{return} CAction the action currently being executed, null if no active action.

getCachingStack() method
public CStack getCachingStack(boolean $createIfNull=true)
$createIfNull | boolean | whether to create a stack if it does not exist yet. Defaults to true.
{return} | CStack | stack of COutputCache objects

getClips() method
public CMap getClips()
{return} CMap the list of clips

Returns the list of clips. A clip is a named piece of rendering result that can be inserted at different places.

See Also

  • CClipWidget
getId() method
public string getId()
{return} string ID of the controller

getLayoutFile() method
public string getLayoutFile(mixed $layoutName)
$layoutName | mixed | layout name
{return} | string | the view file for the layout. False if the view file cannot be found

Looks for the view script file for a layout. This method will look for the view under the application's layoutPath. If the view name starts with '/', the view will be looked for under the application's viewPath. If the view name is null, the application's default layout will be used. If the view name is false, this method simply returns false. Since version 1.0.2, the view name can also refer to a path alias if it contains dot characters. Since version 1.0.3, if the controller belongs to a module, the view file will be searched under the module layout path, and if the view name is null, the module default layout will be used.

getModule() method (available since v1.0.3)
public CWebModule getModule()
{return} CWebModule the module that this controller belongs to. It returns null if the controller does not belong to any module

getPageState() method
public mixed getPageState(string $name, mixed $defaultValue=NULL)
$name | string | the state name
$defaultValue | mixed | the value to be returned if the named state is not found
{return} | mixed | the page state value

Returns a persistent page state value. A page state is a variable that is persistent across POST requests of the same page. In order to use persistent page states, the form(s) must be stateful which are generated using CHtml::statefulForm.

See Also

  • setPageState
  • CHtml::statefulForm
getPageTitle() method
public string getPageTitle()
{return} string the page title. Defaults to the controller name and the action name.

getRoute() method (available since v1.1.0)
public string getRoute()
{return} string the route (module ID, controller ID and action ID) of the current request.

getUniqueId() method (available since v1.0.3)
public string getUniqueId()
{return} string the controller ID that is prefixed with the module ID (if any).

getViewFile() method
public string getViewFile(string $viewName)
$viewName | string | name of the view (without file extension)
{return} | string | the view file path, false if the view file does not exist

Looks for the view file according to the given view name. This method will look for the view under the controller's viewPath. If the view name starts with '/', the view will be looked for under the application's viewPath. The view script file is named as "ViewName.php". A localized view file may be returned if internationalization is needed. See CApplication::findLocalizedFile for more details. Since version 1.0.2, the view name can also refer to a path alias if it contains dot characters. Since version 1.0.3, if the controller belongs to a module, the view file will be searched under the module view path.

See Also

  • CApplication::findLocalizedFile
getViewPath() method
public string getViewPath()
{return} string the directory containing the view files for this controller. Defaults to 'protected/views/ControllerID'.

Returns the directory containing view files for this controller. The default implementation returns 'protected/views/ControllerID'. Child classes may override this method to use customized view path. If the controller belongs to a module (since version 1.0.3), the default view path is the module view path appended with the controller ID.

init() method (available since v1.0.1)
public void init()

Initializes the controller. This method is called by the application before the controller starts to execute. You may override this method to perform the needed initialization for the controller.

isCachingStackEmpty() method (available since v1.0.5)
public whether isCachingStackEmpty()
{return} whether the caching stack is empty. If not empty, it means currently there are some output cache in effect. Note, the return result of this method may change when it is called in different output regions, depending on the partition of output caches.

loadPageStates() method
protected array loadPageStates()
{return} array the loaded page states

Loads page states from a hidden input.

missingAction() method
public void missingAction(string $actionID)
$actionID string the missing action name

Handles the request whose action is not recognized. This method is invoked when the controller cannot find the requested action. The default implementation simply throws an exception.

paginate() method
public CPagination paginate(integer $itemCount, integer $pageSize=NULL, string $pageVar=NULL)
$itemCount | integer | the total item count
$pageSize | integer | the page size. See CPagination for default value.
$pageVar | string | the name of the GET variable storing the current page index. See CPagination for default value.
{return} | CPagination | the pagination information

Generates pagination information. This method can be used to generate pagination information given item count and page size. The pagination information can then be passed to pagers for corresponding rendering.

Note: this method has been deprecated since version 1.0.1. You should directly use "new CPagination" to create a pagination object.

processDynamicOutput() method (available since v1.0.4)
public string processDynamicOutput(string $output)
$output | string | output to be processed
{return} | string | the processed output

Postprocesses the dynamic output. This method is internally used. Do not call this method directly.

processOutput() method
public string processOutput(string $output)
$output | string | the output generated by the current action
{return} | string | the output that has been processed.

Postprocesses the output generated by render(). This method is invoked at the end of render() and renderText(). If there are registered client scripts, this method will insert them into the output at appropriate places. If there are dynamic contents, they will also be inserted. This method may also save the persistent page states in hidden fields of stateful forms in the page.

recordCachingAction() method
public void recordCachingAction(string $context, string $method, array $params)
$context | string | a property name of the controller. It refers to an object whose method is being called. If empty it means the controller itself.
$method | string | the method name
$params | array | parameters passed to the method

Records a method call when an output cache is in effect. When the content is served from the output cache, the recorded method will be re-invoked.

See Also

  • COutputCache
redirect() method
public void redirect(mixed $url, boolean $terminate=true, integer $statusCode=302)
$url | mixed | the URL to be redirected to. If the parameter is an array, the first element must be a route to a controller action and the rest are GET parameters in name-value pairs.
$terminate | boolean | whether to terminate the current application after calling this method
$statusCode | integer | the HTTP status code. Defaults to 302. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for details about HTTP status code. This parameter has been available since version 1.0.4.

Redirects the browser to the specified URL or route (controller/action).

refresh() method
public void refresh(boolean $terminate=true, string $anchor='')
$terminate | boolean | whether to terminate the current application after calling this method
$anchor | string | the anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with '#' if you want to specify it. The parameter has been available since version 1.0.7.

Refreshes the current page. The effect of this method call is the same as user pressing the refresh button on the browser (without post data).

render() method
public string render(string $view, array $data=NULL, boolean $return=false)
$view | string | name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data | array | data to be extracted into PHP variables and made available to the view script
$return | boolean | whether the rendering result should be returned instead of being displayed to end users.
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a view with a layout.

This method first calls renderPartial to render the view (called content view). It then renders the layout view which may embed the content view at appropriate place. In the layout view, the content view rendering result can be accessed via variable $content. At the end, it calls processOutput to insert scripts and dynamic contents if they are available.

By default, the layout view script is "protected/views/layouts/main.php". This may be customized by changing layout.

See Also

  • renderPartial
  • getLayoutFile
renderDynamic() method
public void renderDynamic(callback $callback)
$callback callback a PHP callback which returns the needed dynamic content. When the callback is specified as a string, it will be first assumed to be a method of the current controller class. If the method does not exist, it is assumed to be a global PHP function. Note, the callback should return the dynamic content instead of echoing it.

Renders dynamic content returned by the specified callback. This method is used together with COutputCache. Dynamic contents will always show as their latest state even if the content surrounding them is being cached. This is especially useful when caching pages that are mostly static but contain some small dynamic regions, such as username or current time. We can use this method to render these dynamic regions to ensure they are always up-to-date.

The first parameter to this method should be a valid PHP callback, while the rest parameters will be passed to the callback.

Note, the callback and its parameter values will be serialized and saved in cache. Make sure they are serializable.

renderDynamicInternal() method
public void renderDynamicInternal(callback $callback, array $params)
$callback | callback | a PHP callback which returns the needed dynamic content.
$params | array | parameters passed to the PHP callback

This method is internally used.

See Also

  • renderDynamic
renderPartial() method
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
$view | string | name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data | array | data to be extracted into PHP variables and made available to the view script
$return | boolean | whether the rendering result should be returned instead of being displayed to end users
$processOutput | boolean | whether the rendering result should be postprocessed using processOutput. This parameter should be set true if renderPartial is the only method used to generate the output when handling a user request.
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a view.

The named view refers to a PHP script (resolved via getViewFile) that is included by this method. If $data is an associative array, it will be extracted as PHP variables and made available to the script.

This method differs from render() in that it does not apply a layout to the rendered result. It is thus mostly used in rendering a partial view, or an AJAX response.

See Also

  • getViewFile
  • processOutput
  • render
renderText() method
public string renderText(string $text, boolean $return=false)
$text | string | the static text string
$return | boolean | whether the rendering result should be returned instead of being displayed to end users.
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a static text string. The string will be inserted in the current controller layout and returned back.

See Also

  • getLayoutFile
replaceDynamicOutput() method
protected string replaceDynamicOutput(array $matches)
$matches | array | matches
{return} | string | the replacement

Replaces the dynamic content placeholders with actual content. This is a callback function used internally.

See Also

  • processOutput
resolveViewFile() method (available since v1.0.3)
public mixed resolveViewFile(string $viewName, string $viewPath, string $basePath)
$viewName | string | the view name
$viewPath | string | the directory that is used to search for a relative view name
$basePath | string | the directory that is used to search for an absolute view name
{return} | mixed | the view file path. False if the view file does not exist.

Finds a view file based on its name. The view name can be in one of the following formats:

  • absolute view: the view name starts with a slash '/'.
  • aliased view: the view name contains dots and refers to a path alias. The view file is determined by calling YiiBase::getPathOfAlias().
  • relative view: otherwise.
For absolute view and relative view, the corresponding view file is a PHP file whose name is the same as the view name. The file is located under a specified directory. This method will call CApplication::findLocalizedFile to search for a localized file, if any.

run() method
public void run(string $actionID)
$actionID string action ID

Runs the named action. Filters specified via filters() will be applied.

See Also

  • filters
  • createAction
  • runAction
runAction() method
public void runAction(CAction $action)
$action CAction action to run

Runs the action after passing through all filters. This method is invoked by runActionWithFilters after all possible filters have been executed and the action starts to run.

runActionWithFilters() method
public void runActionWithFilters(CAction $action, array $filters)
$action | CAction | the action to be executed.
$filters | array | list of filters to be applied to the action.

Runs an action with the specified filters. A filter chain will be created based on the specified filters and the action will be executed then.

See Also

  • filters
  • createAction
  • runAction
savePageStates() method
protected void savePageStates(array $states, string $output)
$states | array | the states to be saved.
$output | string | the output to be modified. Note, this is passed by reference.

Saves page states as a base64 string.

setAction() method
public void setAction(CAction $value)
$value CAction the action currently being executed.

setPageState() method
public void setPageState(string $name, mixed $value, mixed $defaultValue=NULL)
$name | string | the state name
$value | mixed | the page state value
$defaultValue | mixed | the default page state value. If this is the same as the given value, the state will be removed from persistent storage.

Saves a persistent page state value. A page state is a variable that is persistent across POST requests of the same page. In order to use persistent page states, the form(s) must be stateful which are generated using CHtml::statefulForm.

See Also

  • getPageState
  • CHtml::statefulForm
setPageTitle() method
public void setPageTitle(string $value)
$value string the page title.


CCookieCollection

Package | system.web
Inheritance | class CCookieCollection » CMap » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CHttpRequest.php 1844 2010-02-26 23:13:40Z qiang.xue $
CCookieCollection implements a collection class to store cookies.

You normally access it via CHttpRequest::getCookies().

Since CCookieCollection extends from CMap, it can be used like an associative array as follows:
$cookies[$name]=new CHttpCookie($name,$value); // sends a cookie
$value=$cookies[$name]->value; // reads a cookie value
unset($cookies[$name]);  // removes a cookie

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the map | CMap
iterator | CMapIterator | Returns an iterator for traversing the items in the list. | CMap
keys | array | the key list | CMap
readOnly | boolean | whether this map is read-only or not. | CMap
request | CHttpRequest | the request instance | CCookieCollection

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
cookies | array | list of validated cookies | CCookieCollection

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CCookieCollection
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Inserts an item at the specified position. | CCookieCollection
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the map. | CMap
contains() |  | CMap
copyFrom() | Copies iterable data into the map. | CMap
count() | Returns the number of items in the map. | CMap
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CMap
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CMap
getKeys() |  | CMap
getReadOnly() |  | CMap
getRequest() |  | CCookieCollection
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
itemAt() | Returns the item with the specified key. | CMap
mergeArray() | Merges two arrays into one recursively. | CMap
mergeWith() | Merges iterable data into the map. | CMap
offsetExists() | Returns whether there is an element at the specified offset. | CMap
offsetGet() | Returns the element at the specified offset. | CMap
offsetSet() | Sets the element at the specified offset. | CMap
offsetUnset() | Unsets the element at the specified offset. | CMap
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item at the specified position. | CCookieCollection
toArray() |  | CMap

Protected Methods

Hide inherited methods

Method | Description | Defined By
addCookie() | Sends a cookie. | CCookieCollection
getCookies() |  | CCookieCollection
removeCookie() | Deletes a cookie. | CCookieCollection
setReadOnly() |  | CMap

Property Details

cookies property read-only
protected array getCookies()

list of validated cookies

request property read-only
public CHttpRequest getRequest()

the request instance

Method Details

__construct() method
public void __construct(CHttpRequest $request)
$request CHttpRequest owner of this collection.

Constructor.

add() method
public void add(integer $name, mixed $cookie)
$name | integer | the specified position.
$cookie | mixed | new item

Inserts an item at the specified position. This overrides the parent implementation by performing additional operations for each newly added CHttpCookie object.

addCookie() method
protected void addCookie(CHttpCookie $cookie)
$cookie CHttpCookie cook to be sent

Sends a cookie.

getCookies() method
protected array getCookies()
{return} array list of validated cookies

getRequest() method
public CHttpRequest getRequest()
{return} CHttpRequest the request instance

remove() method
public mixed remove(integer $name)
$name | integer | the index of the item to be removed.
{return} | mixed | the removed item.

Removes an item at the specified position. This overrides the parent implementation by performing additional cleanup work when removing a TCookie object.

removeCookie() method
protected void removeCookie(CHttpCookie $cookie)
$cookie CHttpCookie cook to be deleted

Deletes a cookie.


CDataProvider

Package | system.web
Inheritance | abstract class CDataProvider » CComponent
Implements | IDataProvider
Subclasses | CActiveDataProvider
Since | 1.1
Version | $Id: CDataProvider.php 1757 2010-01-28 01:12:13Z qiang.xue $
CDataProvider is a base class that implements the IDataProvider interface.

Derived classes mainly need to implement three methods: fetchData, fetchKeys and calculateTotalItemCount.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
data | array | Returns the data items currently available. | CDataProvider
id | string | the unique ID that uniquely identifies the data provider among all data providers. | CDataProvider
itemCount | integer | Returns the number of data items in the current page. | CDataProvider
keys | array | Returns the key values associated with the data items. | CDataProvider
pagination | CPagination | the pagination object. | CDataProvider
sort | CSort | the sorting object. | CDataProvider
totalItemCount | integer | Returns the total number of data items. | CDataProvider

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getData() | Returns the data items currently available. | CDataProvider
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CDataProvider
getItemCount() | Returns the number of data items in the current page. | CDataProvider
getKeys() | Returns the key values associated with the data items. | CDataProvider
getPagination() |  | CDataProvider
getSort() |  | CDataProvider
getTotalItemCount() | Returns the total number of data items. | CDataProvider
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setData() |  | CDataProvider
setId() |  | CDataProvider
setKeys() |  | CDataProvider
setPagination() |  | CDataProvider
setSort() |  | CDataProvider
setTotalItemCount() | Sets the total number of data items. | CDataProvider

Protected Methods

Hide inherited methods

Method | Description | Defined By
calculateTotalItemCount() | Calculates the total number of data items. | CDataProvider
fetchData() | Fetches the data from the persistent data storage. | CDataProvider
fetchKeys() | Fetches the data item keys from the persistent data storage. | CDataProvider

Property Details

data property
public array getData(boolean $refresh=false)
public void setData(array $value)

Returns the data items currently available.

id property
public string getId()
public void setId(string $value)

the unique ID that uniquely identifies the data provider among all data providers.

itemCount property read-only
public integer getItemCount(boolean $refresh=false)

Returns the number of data items in the current page. This is equivalent to count($provider->getData()). When pagination is set false, this returns the same value as totalItemCount.

keys property
public array getKeys(boolean $refresh=false)
public void setKeys(array $value)

Returns the key values associated with the data items.

pagination property
public CPagination getPagination()
public void setPagination(mixed $value)

the pagination object. If this is false, it means the pagination is disabled.

sort property
public CSort getSort()
public void setSort(mixed $value)

the sorting object. If this is false, it means the sorting is disabled.

totalItemCount property
public integer getTotalItemCount(boolean $refresh=false)
public void setTotalItemCount(integer $value)

Returns the total number of data items. When pagination is set false, this returns the same value as itemCount.

Method Details

calculateTotalItemCount() method
abstract protected integer calculateTotalItemCount()
{return} integer the total number of data items.

Calculates the total number of data items.

fetchData() method
abstract protected array fetchData()
{return} array list of data items

Fetches the data from the persistent data storage.

fetchKeys() method
abstract protected array fetchKeys()
{return} array list of data item keys.

Fetches the data item keys from the persistent data storage.

getData() method
public array getData(boolean $refresh=false)
$refresh | boolean | whether the data should be re-fetched from persistent storage.
{return} | array | the list of data items currently available in this data provider.

Returns the data items currently available.

getId() method
public string getId()
{return} string the unique ID that uniquely identifies the data provider among all data providers.

getItemCount() method
public integer getItemCount(boolean $refresh=false)
$refresh | boolean | whether the number of data items should be re-calculated.
{return} | integer | the number of data items in the current page.

Returns the number of data items in the current page. This is equivalent to count($provider->getData()). When pagination is set false, this returns the same value as totalItemCount.

getKeys() method
public array getKeys(boolean $refresh=false)
$refresh | boolean | whether the keys should be re-calculated.
{return} | array | the list of key values corresponding to data. Each data item in data is uniquely identified by the corresponding key value in this array.

Returns the key values associated with the data items.

getPagination() method
public CPagination getPagination()
{return} CPagination the pagination object. If this is false, it means the pagination is disabled.

getSort() method
public CSort getSort()
{return} CSort the sorting object. If this is false, it means the sorting is disabled.

getTotalItemCount() method
public integer getTotalItemCount(boolean $refresh=false)
$refresh | boolean | whether the total number of data items should be re-calculated.
{return} | integer | total number of possible data items.

Returns the total number of data items. When pagination is set false, this returns the same value as itemCount.

setData() method
public void setData(array $value)
$value array put the data items into this provider.

setId() method
public void setId(string $value)
$value string the unique ID that uniquely identifies the data provider among all data providers.

setKeys() method
public void setKeys(array $value)
$value array put the data item keys into this provider.

setPagination() method
public void setPagination(mixed $value)
$value mixed the pagination to be used by this data provider. This could be a CPagination object or an array used to configure the pagination object. If this is false, it means the pagination should be disabled.

setSort() method
public void setSort(mixed $value)
$value mixed the sorting to be used by this data provider. This could be a CSort object or an array used to configure the sorting object. If this is false, it means the sorting should be disabled.

setTotalItemCount() method (available since v1.1.1)
public void setTotalItemCount(integer $value)
$value integer the total number of data items.

Sets the total number of data items. This method is provided in case when the total number cannot be determined by calculateTotalItemCount.


CDbHttpSession

Package | system.web
Inheritance | class CDbHttpSession » CHttpSession » CApplicationComponent » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate, IApplicationComponent
Since | 1.0
Version | $Id: CDbHttpSession.php 1781 2010-02-01 20:37:46Z qiang.xue $
CDbHttpSession extends CHttpSession by using database as session data storage.

CDbHttpSession stores session data in a DB table named 'YiiSession'. The table name can be changed by setting sessionTableName. If the table does not exist, it will be automatically created if autoCreateSessionTable is set true.

The following is the table structure:

CREATE TABLE YiiSession
(
    id CHAR(32) PRIMARY KEY,
    expire INTEGER,
    data TEXT
)

CDbHttpSession relies on PDO to access database.

By default, it will use an SQLite3 database named 'session-YiiVersion.db' under the application runtime directory. You can also specify connectionID so that it makes use of a DB application component to access database.

When using CDbHttpSession in a production server, we recommend you pre-create the session DB table and set autoCreateSessionTable to be false. This will greatly improve the performance. You may also create a DB index for the 'expire' column in the session table to further improve the performance.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoCreateSessionTable | boolean | whether the session DB table should be automatically created if not exists. | CDbHttpSession
autoStart | boolean | whether the session should be automatically started when the session application component is initialized, defaults to true. | CHttpSession
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
connectionID | string | the ID of a CDbConnection application component. | CDbHttpSession
cookieMode | string | how to use cookie to store session ID. | CHttpSession
cookieParams | array | the session cookie parameters. | CHttpSession
count | integer | the number of session variables | CHttpSession
gCProbability | integer | the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. | CHttpSession
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
isStarted | boolean | whether the session has started | CHttpSession
iterator | CHttpSessionIterator | Returns an iterator for traversing the session variables. | CHttpSession
keys | array | the list of session variable names | CHttpSession
savePath | string | the current session save path, defaults to '/tmp'. | CHttpSession
sessionID | string | the current session ID | CHttpSession
sessionName | string | the current session name | CHttpSession
sessionTableName | string | the name of the DB table to store session content. | CDbHttpSession
timeout | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. | CHttpSession
useCustomStorage | boolean | Returns a value indicating whether to use custom session storage. | CDbHttpSession
useTransparentSessionID | boolean | whether transparent sid support is enabled or not, defaults to false. | CHttpSession

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | the DB connection instance | CDbHttpSession

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds a session variable. | CHttpSession
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all session variables | CHttpSession
close() | Ends the current session and store session data. | CHttpSession
closeSession() | Session close handler. | CHttpSession
contains() |  | CHttpSession
count() | Returns the number of items in the session. | CHttpSession
destroy() | Frees all session variables and destroys all data registered to a session. | CHttpSession
destroySession() | Session destroy handler. | CDbHttpSession
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
gcSession() | Session GC (garbage collection) handler. | CDbHttpSession
getCookieMode() |  | CHttpSession
getCookieParams() |  | CHttpSession
getCount() |  | CHttpSession
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getGCProbability() |  | CHttpSession
getIsInitialized() |  | CApplicationComponent
getIsStarted() |  | CHttpSession
getIterator() | Returns an iterator for traversing the session variables. | CHttpSession
getKeys() |  | CHttpSession
getSavePath() |  | CHttpSession
getSessionID() |  | CHttpSession
getSessionName() |  | CHttpSession
getTimeout() |  | CHttpSession
getUseCustomStorage() | Returns a value indicating whether to use custom session storage. | CDbHttpSession
getUseTransparentSessionID() |  | CHttpSession
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CHttpSession
itemAt() | Returns the session variable value with the session variable name. | CHttpSession
offsetExists() | This method is required by the interface ArrayAccess. | CHttpSession
offsetGet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetSet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetUnset() | This method is required by the interface ArrayAccess. | CHttpSession
open() | Starts the session if it has not started yet. | CHttpSession
openSession() | Session open handler. | CDbHttpSession
raiseEvent() | Raises an event. | CComponent
readSession() | Session read handler. | CDbHttpSession
remove() | Removes a session variable. | CHttpSession
setCookieMode() |  | CHttpSession
setCookieParams() | Sets the session cookie parameters. | CHttpSession
setGCProbability() |  | CHttpSession
setSavePath() |  | CHttpSession
setSessionID() |  | CHttpSession
setSessionName() |  | CHttpSession
setTimeout() |  | CHttpSession
setUseTransparentSessionID() |  | CHttpSession
toArray() |  | CHttpSession
writeSession() | Session write handler. | CDbHttpSession

Protected Methods

Hide inherited methods

Method | Description | Defined By
createSessionTable() | Creates the session DB table. | CDbHttpSession
getDbConnection() |  | CDbHttpSession

Property Details

autoCreateSessionTable property
public boolean $autoCreateSessionTable;

whether the session DB table should be automatically created if not exists. Defaults to true.

See Also

  • sessionTableName
connectionID property
public string $connectionID;

the ID of a CDbConnection application component. If not set, a SQLite database will be automatically created and used. The SQLite database file is is protected/runtime/session-YiiVersion.db.

dbConnection property read-only
protected CDbConnection getDbConnection()

the DB connection instance

sessionTableName property
public string $sessionTableName;

the name of the DB table to store session content. Note, if autoCreateSessionTable is false and you want to create the DB table manually by yourself, you need to make sure the DB table is of the following structure:

(id CHAR(32) PRIMARY KEY, expire INTEGER, data TEXT)

See Also

  • autoCreateSessionTable
useCustomStorage property read-only
public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

Method Details

createSessionTable() method
protected void createSessionTable(CDbConnection $db, string $tableName)
$db | CDbConnection | the database connection
$tableName | string | the name of the table to be created

Creates the session DB table.

destroySession() method
public boolean destroySession(string $id)
$id | string | session ID
{return} | boolean | whether session is destroyed successfully

Session destroy handler. Do not call this method directly.

gcSession() method
public boolean gcSession(integer $maxLifetime)
$maxLifetime | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up.
{return} | boolean | whether session is GCed successfully

Session GC (garbage collection) handler. Do not call this method directly.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance

getUseCustomStorage() method
public boolean getUseCustomStorage()
{return} boolean whether to use custom storage.

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

openSession() method
public boolean openSession(string $savePath, string $sessionName)
$savePath | string | session save path
$sessionName | string | session name
{return} | boolean | whether session is opened successfully

Session open handler. Do not call this method directly.

readSession() method
public string readSession(string $id)
$id | string | session ID
{return} | string | the session data

Session read handler. Do not call this method directly.

writeSession() method
public boolean writeSession(string $id, string $data)
$id | string | session ID
$data | string | session data
{return} | boolean | whether session write is successful

Session write handler. Do not call this method directly.


CExtController

Package | system.web
Inheritance | class CExtController » CController » CBaseController » CComponent
Since | 1.0
Version | $Id: CExtController.php 1678 2010-01-07 21:02:00Z qiang.xue $
CExtController is the base class for controllers distributed as extension.

The main purpose of CExtController is to redefine the viewPath property so that it points to the "views" subdirectory under the directory containing the controller class file.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
action | CAction | the action currently being executed, null if no active action. | CController
cachingStack | CStack | stack of COutputCache objects | CController
clips | CMap | Returns the list of clips. | CController
defaultAction | string | the name of the default action. | CController
id | string | ID of the controller | CController
layout | mixed | the name of the layout to be applied to this controller's views. | CController
module | CWebModule | the module that this controller belongs to. | CController
pageTitle | string | the page title. | CController
route | string | the route (module ID, controller ID and action ID) of the current request. | CController
uniqueId | string | the controller ID that is prefixed with the module ID (if any). | CController
viewPath | string | Returns the directory containing view files for this controller. | CExtController

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() |  | CController
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
accessRules() | Returns the access rules for this controller. | CController
actions() | Returns a list of external action classes. | CController
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
behaviors() | Returns a list of behaviors that this controller should behave as. | CController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearPageStates() | Removes all page states. | CController
createAbsoluteUrl() | Creates an absolute URL for the specified action defined in this controller. | CController
createAction() | Creates the action instance based on the action name. | CController
createUrl() | Creates a relative URL for the specified action defined in this controller. | CController
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filterAccessControl() | The filter method for 'accessControl' filter. | CController
filterAjaxOnly() | The filter method for 'ajaxOnly' filter. | CController
filterPostOnly() | The filter method for 'postOnly' filter. | CController
filters() | Returns the filter configurations. | CController
forward() | Processes the request using another controller action. | CController
getAction() |  | CController
getCachingStack() |  | CController
getClips() | Returns the list of clips. | CController
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CController
getLayoutFile() | Looks for the view script file for a layout. | CController
getModule() |  | CController
getPageState() | Returns a persistent page state value. | CController
getPageTitle() |  | CController
getRoute() |  | CController
getUniqueId() |  | CController
getViewFile() | Looks for the view file according to the given view name. | CController
getViewPath() | Returns the directory containing view files for this controller. | CExtController
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the controller. | CController
isCachingStackEmpty() |  | CController
missingAction() | Handles the request whose action is not recognized. | CController
paginate() | Generates pagination information. | CController
processDynamicOutput() | Postprocesses the dynamic output. | CController
processOutput() | Postprocesses the output generated by render(). | CController
raiseEvent() | Raises an event. | CComponent
recordCachingAction() | Records a method call when an output cache is in effect. | CController
redirect() | Redirects the browser to the specified URL or route (controller/action). | CController
refresh() | Refreshes the current page. | CController
render() | Renders a view with a layout. | CController
renderDynamic() | Renders dynamic content returned by the specified callback. | CController
renderDynamicInternal() | This method is internally used. | CController
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
renderPartial() | Renders a view. | CController
renderText() | Renders a static text string. | CController
resolveViewFile() | Finds a view file based on its name. | CController
run() | Runs the named action. | CController
runAction() | Runs the action after passing through all filters. | CController
runActionWithFilters() | Runs an action with the specified filters. | CController
setAction() |  | CController
setPageState() | Saves a persistent page state value. | CController
setPageTitle() |  | CController
setViewPath() |  | CExtController
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
afterAction() | This method is invoked right after an action is executed. | CController
beforeAction() | This method is invoked right before an action is to be executed (after all possible filters.) | CController
createActionFromMap() | Creates the action instance based on the action map. | CController
loadPageStates() | Loads page states from a hidden input. | CController
replaceDynamicOutput() | Replaces the dynamic content placeholders with actual content. | CController
savePageStates() | Saves page states as a base64 string. | CController

Property Details

viewPath property
public string getViewPath()
public void setViewPath(string $value)

Returns the directory containing view files for this controller. This method overrides the parent implementation by specifying the view path to be the "views" subdirectory under the directory containing the controller class file.

Method Details

getViewPath() method
public string getViewPath()
{return} string the directory containing the view files for this controller.

Returns the directory containing view files for this controller. This method overrides the parent implementation by specifying the view path to be the "views" subdirectory under the directory containing the controller class file.

setViewPath() method (available since v1.0.1)
public void setViewPath(string $value)
$value string the directory containing the view files for this controller.


CFormModel

All Packages | Properties | Methods | Events
Package | system.web
Inheritance | class CFormModel » CModel » CComponent
Implements | ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CFormModel.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFormModel represents a data model that collects HTML form inputs.

Unlike CActiveRecord, the data collected by CFormModel are stored in memory only, instead of database.

To collect user inputs, you may extend CFormModel and define the attributes whose values are to be collected from user inputs. You may override rules() to declare validation rules that should be applied to the attributes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | Returns all attribute values. | CModel
errors | array | Returns the errors for all attribute or a single attribute. | CModel
iterator | CMapIterator | Returns an iterator for traversing the attributes in the model. | CModel
safeAttributeNames | array | Returns the attribute names that are safe to be massively assigned. | CModel
scenario | string | Returns the scenario that this model is used in. | CModel
validators | array | Returns the validators applicable to the current scenario. | CModel

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormModel
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addError() | Adds a new error to the specified attribute. | CModel
addErrors() | Adds a list of errors. | CModel
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
attributeLabels() | Returns the attribute labels. | CModel
attributeNames() | Returns the list of attribute names. | CFormModel
behaviors() | Returns a list of behaviors that this model should behave as. | CModel
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearErrors() | Removes errors for all attributes or a single attribute. | CModel
createValidators() | Creates validator objects based on the specification in rules. | CModel
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
generateAttributeLabel() | Generates a user friendly attribute label. | CModel
getAttributeLabel() | Returns the text label for the specified attribute. | CModel
getAttributes() | Returns all attribute values. | CModel
getError() | Returns the first error of the specified attribute. | CModel
getErrors() | Returns the errors for all attribute or a single attribute. | CModel
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the attributes in the model. | CModel
getSafeAttributeNames() | Returns the attribute names that are safe to be massively assigned. | CModel
getScenario() | Returns the scenario that this model is used in. | CModel
getValidators() | Returns the validators applicable to the current scenario. | CModel
hasErrors() | Returns a value indicating whether there is any validation error. | CModel
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes this model. | CFormModel
isAttributeRequired() | Returns a value indicating whether the attribute is required. | CModel
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | CModel
offsetExists() | Returns whether there is an element at the specified offset. | CModel
offsetGet() | Returns the element at the specified offset. | CModel
offsetSet() | Sets the element at the specified offset. | CModel
offsetUnset() | Unsets the element at the specified offset. | CModel
onAfterValidate() | This event is raised after the validation is performed. | CModel
onBeforeValidate() | This event is raised before the validation is performed. | CModel
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | CModel
raiseEvent() | Raises an event. | CComponent
rules() | Returns the validation rules for attributes. | CModel
setAttributes() | Sets the attribute values in a massive way. | CModel
setScenario() |  | CModel
validate() | Performs the validation. | CModel

Protected Methods

Hide inherited methods

Method | Description | Defined By
afterValidate() | This method is invoked after validation ends. | CModel
beforeValidate() | This method is invoked before validation starts. | CModel

Events

Hide inherited events

Event | Description | Defined By
onBeforeValidate | This event is raised before the validation is performed. | CModel
onAfterValidate | This event is raised after the validation is performed. | CModel
onUnsafeAttribute | This method is invoked when an unsafe attribute is being massively assigned. | CModel

Method Details

__construct() method
public void __construct(string $scenario='')
$scenario string name of the scenario that this model is used in. See CModel::scenario on how scenario is used by models.

Constructor.

See Also

  • getScenario
attributeNames() method
public array attributeNames()
{return} array list of attribute names. Defaults to all public properties of the class.

Returns the list of attribute names. By default, this method returns all public properties of the class. You may override this method to change the default.

init() method (available since v1.0.8)
public void init()

Initializes this model. This method is invoked in the constructor right after scenario is set. You may override this method to provide code that is needed to initialize the model (e.g. setting initial property values.)


CHttpCookie

Package | system.web
Inheritance | class CHttpCookie » CComponent
Since | 1.0
Version | $Id: CHttpCookie.php 1678 2010-01-07 21:02:00Z qiang.xue $
A CHttpCookie instance stores a single cookie, including the cookie name, value, domain, path, expire, and secure.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
domain | string | domain of the cookie | CHttpCookie
expire | integer | the timestamp at which the cookie expires. | CHttpCookie
httpOnly | boolean | whether the cookie should be accessible only through the HTTP protocol. | CHttpCookie
name | string | name of the cookie | CHttpCookie
path | string | the path on the server in which the cookie will be available on. | CHttpCookie
secure | boolean | whether cookie should be sent via secure connection | CHttpCookie
value | string | value of the cookie | CHttpCookie

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CHttpCookie
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

domain property
public string $domain;

domain of the cookie

expire property
public integer $expire;

the timestamp at which the cookie expires. This is the server timestamp. Defaults to 0, meaning "until the browser is closed".

httpOnly property
public boolean $httpOnly;

whether the cookie should be accessible only through the HTTP protocol. By setting this property to true, the cookie will not be accessible by scripting languages, such as JavaScript, which can effectly help to reduce identity theft through XSS attacks. Note, this property is only effective for PHP 5.2.0 or above.

name property
public string $name;

name of the cookie

path property
public string $path;

the path on the server in which the cookie will be available on. The default is '/'.

secure property
public boolean $secure;

whether cookie should be sent via secure connection

value property
public string $value;

value of the cookie

Method Details

__construct() method
public void __construct(string $name, string $value)
$name | string | name of this cookie
$value | string | value of this cookie

Constructor.


CHttpRequest

Package | system.web
Inheritance | class CHttpRequest » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CHttpRequest.php 1844 2010-02-26 23:13:40Z qiang.xue $
CHttpRequest encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.

CHttpRequest also manages the cookies sent from and sent to the user. By setting enableCookieValidation to true, cookies sent from the user will be validated to see if they are tampered. The property cookies returns the collection of cookies. For more details, see CCookieCollection.

CHttpRequest is a default application component loaded by CWebApplication. It can be accessed via CWebApplication::getRequest().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
acceptTypes | string | user browser accept types | CHttpRequest
baseUrl | string | Returns the relative URL for the application. | CHttpRequest
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
browser | array | Returns information about the capabilities of user browser. | CHttpRequest
cookies | CCookieCollection | Returns the cookie collection. | CHttpRequest
csrfCookie | array | the property values (in name-value pairs) used to initialize the CSRF cookie. | CHttpRequest
csrfToken | string | Returns the random token used to perform CSRF validation. | CHttpRequest
csrfTokenName | string | the name of the token used to prevent CSRF. | CHttpRequest
enableCookieValidation | boolean | whether cookies should be validated to ensure they are not tampered. | CHttpRequest
enableCsrfValidation | boolean | whether to enable CSRF (Cross-Site Request Forgery) validation. | CHttpRequest
hostInfo | string | Returns the schema and host part of the application URL. | CHttpRequest
isAjaxRequest | boolean | whether this is an AJAX (XMLHttpRequest) request. | CHttpRequest
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
isPostRequest | boolean | whether this is POST request. | CHttpRequest
isSecureConnection | boolean | if the request is sent via secure channel (https) | CHttpRequest
pathInfo | string | Returns the path info of the currently requested URL. | CHttpRequest
preferredLanguage | string | the user preferred language. | CHttpRequest
queryString | string | part of the request URL that is after the question mark | CHttpRequest
requestType | string | request type, such as GET, POST, HEAD, PUT, DELETE. | CHttpRequest
requestUri | string | Returns the request URI portion for the currently requested URL. | CHttpRequest
scriptFile | string | entry script file path (processed w/ realpath()) | CHttpRequest
scriptUrl | string | Returns the relative URL of the entry script. | CHttpRequest
serverName | string | server name | CHttpRequest
serverPort | integer | server port number | CHttpRequest
url | string | part of the request URL after the host info. | CHttpRequest
urlReferrer | string | URL referrer, null if not present | CHttpRequest
userAgent | string | user agent | CHttpRequest
userHost | string | user host name, null if cannot be determined | CHttpRequest
userHostAddress | string | user IP address | CHttpRequest

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getAcceptTypes() |  | CHttpRequest
getBaseUrl() | Returns the relative URL for the application. | CHttpRequest
getBrowser() | Returns information about the capabilities of user browser. | CHttpRequest
getCookies() | Returns the cookie collection. | CHttpRequest
getCsrfToken() | Returns the random token used to perform CSRF validation. | CHttpRequest
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHostInfo() | Returns the schema and host part of the application URL. | CHttpRequest
getIsAjaxRequest() |  | CHttpRequest
getIsInitialized() |  | CApplicationComponent
getIsPostRequest() |  | CHttpRequest
getIsSecureConnection() |  | CHttpRequest
getParam() | Returns the named GET or POST parameter value. | CHttpRequest
getPathInfo() | Returns the path info of the currently requested URL. | CHttpRequest
getPost() | Returns the named POST parameter value. | CHttpRequest
getPreferredLanguage() |  | CHttpRequest
getQuery() | Returns the named GET parameter value. | CHttpRequest
getQueryString() |  | CHttpRequest
getRequestType() |  | CHttpRequest
getRequestUri() | Returns the request URI portion for the currently requested URL. | CHttpRequest
getScriptFile() |  | CHttpRequest
getScriptUrl() | Returns the relative URL of the entry script. | CHttpRequest
getServerName() |  | CHttpRequest
getServerPort() |  | CHttpRequest
getUrl() |  | CHttpRequest
getUrlReferrer() |  | CHttpRequest
getUserAgent() |  | CHttpRequest
getUserHost() |  | CHttpRequest
getUserHostAddress() |  | CHttpRequest
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CHttpRequest
raiseEvent() | Raises an event. | CComponent
redirect() | Redirects the browser to the specified URL. | CHttpRequest
sendFile() | Sends a file to user. | CHttpRequest
setBaseUrl() | Sets the relative URL for the application. | CHttpRequest
setHostInfo() | Sets the schema and host part of the application URL. | CHttpRequest
setScriptUrl() | Sets the relative URL for the application entry script. | CHttpRequest
stripSlashes() | Strips slashes from input data. | CHttpRequest
validateCsrfToken() | Performs the CSRF validation. | CHttpRequest

Protected Methods

Hide inherited methods

Method | Description | Defined By
createCsrfCookie() | Creates a cookie with a randomly generated CSRF token. | CHttpRequest
normalizeRequest() | Normalizes the request data. | CHttpRequest

Property Details

acceptTypes property read-only
public string getAcceptTypes()

user browser accept types

baseUrl property
public string getBaseUrl(boolean $absolute=false)
public void setBaseUrl(string $value)

Returns the relative URL for the application. This is similar to scriptUrl except that it does not have the script file name, and the ending slashes are stripped off.

See Also

  • setScriptUrl
browser property read-only
public array getBrowser(string $userAgent=NULL)

Returns information about the capabilities of user browser.

See Also

  • http://www.php.net/manual/en/function.get-browser.php
cookies property read-only
public CCookieCollection getCookies()

Returns the cookie collection. The result can be used like an associative array. Adding CHttpCookie objects to the collection will send the cookies to the client; and removing the objects from the collection will delete those cookies on the client.

csrfCookie property
public array $csrfCookie;

the property values (in name-value pairs) used to initialize the CSRF cookie. Any property of CHttpCookie may be initialized. This property is effective only when enableCsrfValidation is true.

csrfToken property read-only
public string getCsrfToken()

Returns the random token used to perform CSRF validation. The token will be read from cookie first. If not found, a new token will be generated.

See Also

  • enableCsrfValidation
csrfTokenName property
public string $csrfTokenName;

the name of the token used to prevent CSRF. Defaults to 'YII_CSRF_TOKEN'. This property is effectively only when enableCsrfValidation is true.

enableCookieValidation property
public boolean $enableCookieValidation;

whether cookies should be validated to ensure they are not tampered. Defaults to false.

enableCsrfValidation property
public boolean $enableCsrfValidation;

whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to false. By setting this property to true, forms submitted to an Yii Web application must be originated from the same application. If not, a 400 HTTP exception will be raised. Note, this feature requires that the user client accepts cookie. You also need to use CHtml::form or CHtml::statefulForm to generate the needed HTML forms in your pages.

See Also

  • http://freedom-to-tinker.com/sites/default/files/csrf.pdf
hostInfo property
public string getHostInfo(string $schema='')
public void setHostInfo(string $value)

Returns the schema and host part of the application URL. The returned URL does not have an ending slash. By default this is determined based on the user request information. You may explicitly specify it by setting the hostInfo property.

See Also

  • setHostInfo
isAjaxRequest property read-only
public boolean getIsAjaxRequest()

whether this is an AJAX (XMLHttpRequest) request.

isPostRequest property read-only
public boolean getIsPostRequest()

whether this is POST request.

isSecureConnection property read-only
public boolean getIsSecureConnection()

if the request is sent via secure channel (https)

pathInfo property read-only
public string getPathInfo()

Returns the path info of the currently requested URL. This refers to the part that is after the entry script and before the question mark. The starting and ending slashes are stripped off.

preferredLanguage property read-only
public string getPreferredLanguage()

the user preferred language. The returned language ID will be canonicalized using CLocale::getCanonicalID. This method returns false if the user does not have language preference.

queryString property read-only
public string getQueryString()

part of the request URL that is after the question mark

requestType property read-only
public string getRequestType()

request type, such as GET, POST, HEAD, PUT, DELETE.

requestUri property read-only (available since v1.0.1)
public string getRequestUri()

Returns the request URI portion for the currently requested URL. This refers to the portion that is after the host info part. It includes the query string part if any. The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

scriptFile property read-only
public string getScriptFile()

entry script file path (processed w/ realpath())

scriptUrl property
public string getScriptUrl()
public void setScriptUrl(string $value)

Returns the relative URL of the entry script. The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

serverName property read-only
public string getServerName()

server name

serverPort property read-only
public integer getServerPort()

server port number

url property read-only
public string getUrl()

part of the request URL after the host info. It consists of the following parts:

  • scriptUrl
  • pathInfo
  • queryString

urlReferrer property read-only
public string getUrlReferrer()

URL referrer, null if not present

userAgent property read-only
public string getUserAgent()

user agent

userHost property read-only
public string getUserHost()

user host name, null if cannot be determined

userHostAddress property read-only
public string getUserHostAddress()

user IP address

Method Details

createCsrfCookie() method
protected CHttpCookie createCsrfCookie()
{return} CHttpCookie the generated cookie

Creates a cookie with a randomly generated CSRF token. Initial values specified in csrfCookie will be applied to the generated cookie.

See Also

  • enableCsrfValidation
getAcceptTypes() method
public string getAcceptTypes()
{return} string user browser accept types

getBaseUrl() method
public string getBaseUrl(boolean $absolute=false)
$absolute | boolean | whether to return an absolute URL. Defaults to false, meaning returning a relative one. This parameter has been available since 1.0.2.
{return} | string | the relative URL for the application

Returns the relative URL for the application. This is similar to scriptUrl except that it does not have the script file name, and the ending slashes are stripped off.

See Also

  • setScriptUrl
getBrowser() method
public array getBrowser(string $userAgent=NULL)
$userAgent | string | the user agent to be analyzed. Defaults to null, meaning using the current User-Agent HTTP header information.
{return} | array | user browser capabilities.

Returns information about the capabilities of user browser.

See Also

  • http://www.php.net/manual/en/function.get-browser.php
getCookies() method
public CCookieCollection getCookies()
{return} CCookieCollection the cookie collection.

Returns the cookie collection. The result can be used like an associative array. Adding CHttpCookie objects to the collection will send the cookies to the client; and removing the objects from the collection will delete those cookies on the client.

getCsrfToken() method
public string getCsrfToken()
{return} string the random token for CSRF validation.

Returns the random token used to perform CSRF validation. The token will be read from cookie first. If not found, a new token will be generated.

See Also

  • enableCsrfValidation
getHostInfo() method
public string getHostInfo(string $schema='')
$schema | string | schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
{return} | string | schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com)

Returns the schema and host part of the application URL. The returned URL does not have an ending slash. By default this is determined based on the user request information. You may explicitly specify it by setting the hostInfo property.

See Also

  • setHostInfo
getIsAjaxRequest() method
public boolean getIsAjaxRequest()
{return} boolean whether this is an AJAX (XMLHttpRequest) request.

getIsPostRequest() method
public boolean getIsPostRequest()
{return} boolean whether this is POST request.

getIsSecureConnection() method
public boolean getIsSecureConnection()
{return} boolean if the request is sent via secure channel (https)

getParam() method (available since v1.0.4)
public mixed getParam(string $name, mixed $defaultValue=NULL)
$name | string | the GET parameter name
$defaultValue | mixed | the default parameter value if the GET parameter does not exist.
{return} | mixed | the GET parameter value

Returns the named GET or POST parameter value. If the GET or POST parameter does not exist, the second parameter to this method will be returned. If both GET and POST contains such a named parameter, the GET parameter takes precedence.

See Also

  • getQuery
  • getPost
getPathInfo() method
public string getPathInfo()
{return} string part of the request URL that is after the entry script and before the question mark.

Returns the path info of the currently requested URL. This refers to the part that is after the entry script and before the question mark. The starting and ending slashes are stripped off.

getPost() method (available since v1.0.4)
public mixed getPost(string $name, mixed $defaultValue=NULL)
$name | string | the POST parameter name
$defaultValue | mixed | the default parameter value if the POST parameter does not exist.
{return} | mixed | the POST parameter value

Returns the named POST parameter value. If the POST parameter does not exist, the second parameter to this method will be returned.

See Also

  • getParam
  • getQuery
getPreferredLanguage() method
public string getPreferredLanguage()
{return} string the user preferred language. The returned language ID will be canonicalized using CLocale::getCanonicalID. This method returns false if the user does not have language preference.

getQuery() method (available since v1.0.4)
public mixed getQuery(string $name, mixed $defaultValue=NULL)
$name | string | the GET parameter name
$defaultValue | mixed | the default parameter value if the GET parameter does not exist.
{return} | mixed | the GET parameter value

Returns the named GET parameter value. If the GET parameter does not exist, the second parameter to this method will be returned.

See Also

  • getPost
  • getParam
getQueryString() method
public string getQueryString()
{return} string part of the request URL that is after the question mark

getRequestType() method
public string getRequestType()
{return} string request type, such as GET, POST, HEAD, PUT, DELETE.

getRequestUri() method (available since v1.0.1)
public string getRequestUri()
{return} string the request URI portion for the currently requested URL.

Returns the request URI portion for the currently requested URL. This refers to the portion that is after the host info part. It includes the query string part if any. The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

getScriptFile() method
public string getScriptFile()
{return} string entry script file path (processed w/ realpath())

getScriptUrl() method
public string getScriptUrl()
{return} string the relative URL of the entry script.

Returns the relative URL of the entry script. The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

getServerName() method
public string getServerName()
{return} string server name

getServerPort() method
public integer getServerPort()
{return} integer server port number

getUrl() method
public string getUrl()
{return} string part of the request URL after the host info. It consists of the following parts:
  • scriptUrl
  • pathInfo
  • queryString

getUrlReferrer() method
public string getUrlReferrer()
{return} string URL referrer, null if not present

getUserAgent() method
public string getUserAgent()
{return} string user agent

getUserHost() method
public string getUserHost()
{return} string user host name, null if cannot be determined

getUserHostAddress() method
public string getUserHostAddress()
{return} string user IP address

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by preprocessing the user request data.

normalizeRequest() method
protected void normalizeRequest()

Normalizes the request data. This method strips off slashes in request data if get_magic_quotes_gpc() returns true. It also performs CSRF validation if enableCsrfValidation is true.

redirect() method
public void redirect(string $url, boolean $terminate=true, integer $statusCode=302)
$url | string | URL to be redirected to. If the URL is a relative one, the base URL of the application will be inserted at the beginning.
$terminate | boolean | whether to terminate the current application
$statusCode | integer | the HTTP status code. Defaults to 302. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for details about HTTP status code. This parameter has been available since version 1.0.4.

Redirects the browser to the specified URL.

sendFile() method
public void sendFile(string $fileName, string $content, string $mimeType=NULL, boolean $terminate=true)
$fileName | string | file name
$content | string | content to be set.
$mimeType | string | mime type of the content. If null, it will be guessed automatically based on the given file name.
$terminate | boolean | whether to terminate the current application after calling this method

Sends a file to user.

setBaseUrl() method
public void setBaseUrl(string $value)
$value string the relative URL for the application

Sets the relative URL for the application. By default the URL is determined based on the entry script URL. This setter is provided in case you want to change this behavior.

setHostInfo() method
public void setHostInfo(string $value)
$value string the schema and host part of the application URL.

Sets the schema and host part of the application URL. This setter is provided in case the schema and hostname cannot be determined on certain Web servers.

setScriptUrl() method
public void setScriptUrl(string $value)
$value string the relative URL for the application entry script.

Sets the relative URL for the application entry script. This setter is provided in case the entry script URL cannot be determined on certain Web servers.

stripSlashes() method
public mixed stripSlashes(mixed $data)
$data | mixed | input data to be processed
{return} | mixed | processed data

Strips slashes from input data. This method is applied when magic quotes is enabled.

validateCsrfToken() method (available since v1.0.4)
public void validateCsrfToken(CEvent $event)
$event CEvent event parameter

Performs the CSRF validation. This is the event handler responding to CApplication::onBeginRequest. The default implementation will compare the CSRF token obtained from a cookie and from a POST field. If they are different, a CSRF attack is detected.


CHttpSession

Package | system.web
Inheritance | class CHttpSession » CApplicationComponent » CComponent
Implements | IApplicationComponent, IteratorAggregate, Traversable, ArrayAccess, Countable
Subclasses | CCacheHttpSession, CDbHttpSession
Since | 1.0
Version | $Id: CHttpSession.php 1678 2010-01-07 21:02:00Z qiang.xue $
CHttpSession provides session-level data management and the related configurations.

To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().

If autoStart is set true, the session will be started automatically when the application component is initialized by the application.

CHttpSession can be used like an array to set and get session data. For example,
  $session=new CHttpSession;
  $session->open();
  $value1=$session['name1'];  // get session variable 'name1'
  $value2=$session['name2'];  // get session variable 'name2'
  foreach($session as $name=>$value) // traverse all session variables
  $session['name3']=$value3;  // set session variable 'name3'

The following configurations are available for session:
  • sessionID;
  • sessionName;
  • autoStart;
  • savePath;
  • cookieParams;
  • gcProbability;
  • cookieMode;
  • useTransparentSessionID;
  • timeout.
See the corresponding setter and getter documentation for more information. Note, these properties must be set before the session is started.

CHttpSession can be extended to support customized session storage. Override openSession, closeSession, readSession, writeSession, destroySession and gcSession and set useCustomStorage to true. Then, the session data will be stored and retrieved using the above methods.

CHttpSession is a Web application component that can be accessed via CWebApplication::getSession().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
autoStart | boolean | whether the session should be automatically started when the session application component is initialized, defaults to true. | CHttpSession
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cookieMode | string | how to use cookie to store session ID. | CHttpSession
cookieParams | array | the session cookie parameters. | CHttpSession
count | integer | the number of session variables | CHttpSession
gCProbability | integer | the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. | CHttpSession
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
isStarted | boolean | whether the session has started | CHttpSession
iterator | CHttpSessionIterator | Returns an iterator for traversing the session variables. | CHttpSession
keys | array | the list of session variable names | CHttpSession
savePath | string | the current session save path, defaults to '/tmp'. | CHttpSession
sessionID | string | the current session ID | CHttpSession
sessionName | string | the current session name | CHttpSession
timeout | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. | CHttpSession
useCustomStorage | boolean | Returns a value indicating whether to use custom session storage. | CHttpSession
useTransparentSessionID | boolean | whether transparent sid support is enabled or not, defaults to false. | CHttpSession

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds a session variable. | CHttpSession
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all session variables | CHttpSession
close() | Ends the current session and store session data. | CHttpSession
closeSession() | Session close handler. | CHttpSession
contains() |  | CHttpSession
count() | Returns the number of items in the session. | CHttpSession
destroy() | Frees all session variables and destroys all data registered to a session. | CHttpSession
destroySession() | Session destroy handler. | CHttpSession
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
gcSession() | Session GC (garbage collection) handler. | CHttpSession
getCookieMode() |  | CHttpSession
getCookieParams() |  | CHttpSession
getCount() |  | CHttpSession
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getGCProbability() |  | CHttpSession
getIsInitialized() |  | CApplicationComponent
getIsStarted() |  | CHttpSession
getIterator() | Returns an iterator for traversing the session variables. | CHttpSession
getKeys() |  | CHttpSession
getSavePath() |  | CHttpSession
getSessionID() |  | CHttpSession
getSessionName() |  | CHttpSession
getTimeout() |  | CHttpSession
getUseCustomStorage() | Returns a value indicating whether to use custom session storage. | CHttpSession
getUseTransparentSessionID() |  | CHttpSession
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CHttpSession
itemAt() | Returns the session variable value with the session variable name. | CHttpSession
offsetExists() | This method is required by the interface ArrayAccess. | CHttpSession
offsetGet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetSet() | This method is required by the interface ArrayAccess. | CHttpSession
offsetUnset() | This method is required by the interface ArrayAccess. | CHttpSession
open() | Starts the session if it has not started yet. | CHttpSession
openSession() | Session open handler. | CHttpSession
raiseEvent() | Raises an event. | CComponent
readSession() | Session read handler. | CHttpSession
remove() | Removes a session variable. | CHttpSession
setCookieMode() |  | CHttpSession
setCookieParams() | Sets the session cookie parameters. | CHttpSession
setGCProbability() |  | CHttpSession
setSavePath() |  | CHttpSession
setSessionID() |  | CHttpSession
setSessionName() |  | CHttpSession
setTimeout() |  | CHttpSession
setUseTransparentSessionID() |  | CHttpSession
toArray() |  | CHttpSession
writeSession() | Session write handler. | CHttpSession

Property Details

autoStart property
public boolean $autoStart;

whether the session should be automatically started when the session application component is initialized, defaults to true.

cookieMode property
public string getCookieMode()
public void setCookieMode(string $value)

how to use cookie to store session ID. Defaults to 'Allow'.

cookieParams property
public array getCookieParams()
public void setCookieParams(array $value)

the session cookie parameters.

See Also

  • http://us2.php.net/manual/en/function.session-get-cookie-params.php
count property read-only
public integer getCount()

the number of session variables

gCProbability property
public integer getGCProbability()
public void setGCProbability(integer $value)

the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.

isStarted property read-only
public boolean getIsStarted()

whether the session has started

iterator property read-only
public CHttpSessionIterator getIterator()

Returns an iterator for traversing the session variables. This method is required by the interface IteratorAggregate.

keys property read-only
public array getKeys()

the list of session variable names

savePath property
public string getSavePath()
public void setSavePath(string $value)

the current session save path, defaults to '/tmp'.

sessionID property
public string getSessionID()
public void setSessionID(string $value)

the current session ID

sessionName property
public string getSessionName()
public void setSessionName(string $value)

the current session name

timeout property
public integer getTimeout()
public void setTimeout(integer $value)

the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.

useCustomStorage property read-only
public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method should be overriden to return true if custom session storage handler should be used. If returning true, make sure the methods openSession, closeSession, readSession, writeSession, destroySession, and gcSession are overridden in child class, because they will be used as the callback handlers. The default implementation always return false.

useTransparentSessionID property
public boolean getUseTransparentSessionID()
public void setUseTransparentSessionID(boolean $value)

whether transparent sid support is enabled or not, defaults to false.

Method Details

add() method
public void add(mixed $key, mixed $value)
$key | mixed | session variable name
$value | mixed | session variable value

Adds a session variable. Note, if the specified name already exists, the old value will be removed first.

clear() method
public void clear()

Removes all session variables

close() method
public void close()

Ends the current session and store session data.

closeSession() method
public boolean closeSession()
{return} boolean whether session is closed successfully

Session close handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

contains() method
public boolean contains(mixed $key)
$key | mixed | session variable name
{return} | boolean | whether there is the named session variable

count() method
public integer count()
{return} integer number of items in the session.

Returns the number of items in the session. This method is required by Countable interface.

destroy() method
public void destroy()

Frees all session variables and destroys all data registered to a session.

destroySession() method
public boolean destroySession(string $id)
$id | string | session ID
{return} | boolean | whether session is destroyed successfully

Session destroy handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

gcSession() method
public boolean gcSession(integer $maxLifetime)
$maxLifetime | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up.
{return} | boolean | whether session is GCed successfully

Session GC (garbage collection) handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

getCookieMode() method
public string getCookieMode()
{return} string how to use cookie to store session ID. Defaults to 'Allow'.

getCookieParams() method
public array getCookieParams()
{return} array the session cookie parameters.

See Also

  • http://us2.php.net/manual/en/function.session-get-cookie-params.php
getCount() method
public integer getCount()
{return} integer the number of session variables

getGCProbability() method
public integer getGCProbability()
{return} integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.

getIsStarted() method
public boolean getIsStarted()
{return} boolean whether the session has started

getIterator() method
public CHttpSessionIterator getIterator()
{return} CHttpSessionIterator an iterator for traversing the session variables.

Returns an iterator for traversing the session variables. This method is required by the interface IteratorAggregate.

getKeys() method
public array getKeys()
{return} array the list of session variable names

getSavePath() method
public string getSavePath()
{return} string the current session save path, defaults to '/tmp'.

getSessionID() method
public string getSessionID()
{return} string the current session ID

getSessionName() method
public string getSessionName()
{return} string the current session name

getTimeout() method
public integer getTimeout()
{return} integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.

getUseCustomStorage() method
public boolean getUseCustomStorage()
{return} boolean whether to use custom storage.

Returns a value indicating whether to use custom session storage. This method should be overriden to return true if custom session storage handler should be used. If returning true, make sure the methods openSession, closeSession, readSession, writeSession, destroySession, and gcSession are overridden in child class, because they will be used as the callback handlers. The default implementation always return false.

getUseTransparentSessionID() method
public boolean getUseTransparentSessionID()
{return} boolean whether transparent sid support is enabled or not, defaults to false.

init() method
public void init()

Initializes the application component. This method is required by IApplicationComponent and is invoked by application.

itemAt() method
public mixed itemAt(mixed $key)
$key | mixed | the session variable name
{return} | mixed | the session variable value, null if no such variable exists

Returns the session variable value with the session variable name. This method is exactly the same as offsetGet.

offsetExists() method
public boolean offsetExists(mixed $offset)
$offset | mixed | the offset to check on
{return} | boolean |

This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(integer $offset)
$offset | integer | the offset to retrieve element.
{return} | mixed | the element at the offset, null if no element is found at the offset

This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(integer $offset, mixed $item)
$offset | integer | the offset to set element
$item | mixed | the element value

This method is required by the interface ArrayAccess.

offsetUnset() method
public void offsetUnset(mixed $offset)
$offset mixed the offset to unset element

This method is required by the interface ArrayAccess.

open() method
public void open()

Starts the session if it has not started yet.

openSession() method
public boolean openSession(string $savePath, string $sessionName)
$savePath | string | session save path
$sessionName | string | session name
{return} | boolean | whether session is opened successfully

Session open handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

readSession() method
public string readSession(string $id)
$id | string | session ID
{return} | string | the session data

Session read handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

remove() method
public mixed remove(mixed $key)
$key | mixed | the name of the session variable to be removed
{return} | mixed | the removed value, null if no such session variable.

Removes a session variable.

setCookieMode() method
public void setCookieMode(string $value)
$value string how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'.

setCookieParams() method
public void setCookieParams(array $value)
$value array cookie parameters, valid keys include: lifetime, path, domain, secure.

Sets the session cookie parameters. The effect of this method only lasts for the duration of the script. Call this method before the session starts.

See Also

  • http://us2.php.net/manual/en/function.session-set-cookie-params.php
setGCProbability() method
public void setGCProbability(integer $value)
$value integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization.

setSavePath() method
public void setSavePath(string $value)
$value string the current session save path

setSessionID() method
public void setSessionID(string $value)
$value string the session ID for the current session

setSessionName() method
public void setSessionName(string $value)
$value string the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID

setTimeout() method
public void setTimeout(integer $value)
$value integer the number of seconds after which data will be seen as 'garbage' and cleaned up

setUseTransparentSessionID() method
public void setUseTransparentSessionID(boolean $value)
$value boolean whether transparent sid support is enabled or not.

toArray() method
public array toArray()
{return} array the list of all session variables in array

writeSession() method
public boolean writeSession(string $id, string $data)
$id | string | session ID
$data | string | session data
{return} | boolean | whether session write is successful

Session write handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.


CHttpSessionIterator

All Packages | Methods
Package | system.web
Inheritance | class CHttpSessionIterator
Implements | Iterator, Traversable
Since | 1.0
Version | $Id: CHttpSessionIterator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CHttpSessionIterator implements an interator for CHttpSession.

It allows CHttpSession to return a new iterator for traversing the session variables.

Public Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CHttpSessionIterator
current() | Returns the current array element. | CHttpSessionIterator
key() | Returns the key of the current array element. | CHttpSessionIterator
next() | Moves the internal pointer to the next array element. | CHttpSessionIterator
rewind() | Rewinds internal array pointer. | CHttpSessionIterator
valid() | Returns whether there is an element at current position. | CHttpSessionIterator

Method Details

__construct() method
public void __construct()

Constructor.

current() method
public mixed current()
{return} mixed the current array element

Returns the current array element. This method is required by the interface Iterator.

key() method
public mixed key()
{return} mixed the key of the current array element

Returns the key of the current array element. This method is required by the interface Iterator.

next() method
public void next()

Moves the internal pointer to the next array element. This method is required by the interface Iterator.

rewind() method
public void rewind()

Rewinds internal array pointer. This method is required by the interface Iterator.

valid() method
public boolean valid()
{return} boolean

Returns whether there is an element at current position. This method is required by the interface Iterator.


COutputEvent

Package | system.web
Inheritance | class COutputEvent » CEvent » CComponent
Since | 1.0
Version | $Id: COutputEvent.php 1678 2010-01-07 21:02:00Z qiang.xue $
COutputEvent represents the parameter for events related with output handling.

An event handler may retrieve the captured output for further processing.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
handled | boolean | whether the event is handled. | CEvent
output | string | the output to be processed. | COutputEvent
sender | object | the sender of this event | CEvent

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | COutputEvent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

output property
public string $output;

the output to be processed. The processed output should be stored back to this property.

Method Details

__construct() method
public void __construct(mixed $sender, string $output)
$sender | mixed | sender of the event
$output | string | the output to be processed

Constructor.


CPagination

Package | system.web
Inheritance | class CPagination » CComponent
Since | 1.0
Version | $Id: CPagination.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPagination represents information relevant to pagination.

When data needs to be rendered in multiple pages, we can use CPagination to represent information such as total item count, page size, current page, etc. These information can be passed to pagers to render pagination buttons or links.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
currentPage | integer | the zero-based index of the current page. | CPagination
itemCount | integer | total number of items. | CPagination
limit | integer | the limit of the data. | CPagination
offset | integer | the offset of the data. | CPagination
pageCount | integer | number of pages | CPagination
pageSize | integer | number of items in each page. | CPagination
pageVar | string | name of the GET variable storing the current page index. | CPagination
params | array | the additional GET parameters (name=>value) that should be used when generating pagination URLs. | CPagination
route | string | the route (controller ID and action ID) for displaying the paged contents. | CPagination

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CPagination
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyLimit() | Applies LIMIT and OFFSET to the specified query criteria. | CPagination
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createPageUrl() | Creates the URL suitable for pagination. | CPagination
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCurrentPage() |  | CPagination
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getItemCount() |  | CPagination
getLimit() |  | CPagination
getOffset() |  | CPagination
getPageCount() |  | CPagination
getPageSize() |  | CPagination
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setCurrentPage() |  | CPagination
setItemCount() |  | CPagination
setPageSize() |  | CPagination

Property Details

currentPage property
public integer getCurrentPage(boolean $recalculate=true)
public void setCurrentPage(integer $value)

the zero-based index of the current page. Defaults to 0.

itemCount property
public integer getItemCount()
public void setItemCount(integer $value)

total number of items. Defaults to 0.

limit property read-only (available since v1.1.0)
public integer getLimit()

the limit of the data. This may be used to set the LIMIT value for a SQL statement for fetching the current page of data. This returns the same value as pageSize.

offset property read-only (available since v1.1.0)
public integer getOffset()

the offset of the data. This may be used to set the OFFSET value for a SQL statement for fetching the current page of data.

pageCount property read-only
public integer getPageCount()

number of pages

pageSize property
public integer getPageSize()
public void setPageSize(integer $value)

number of items in each page. Defaults to 10.

pageVar property
public string $pageVar;

name of the GET variable storing the current page index. Defaults to 'page'.

params property (available since v1.0.9)
public array $params;

the additional GET parameters (name=>value) that should be used when generating pagination URLs. Defaults to null, meaning using the currently available GET parameters.

route property
public string $route;

the route (controller ID and action ID) for displaying the paged contents. Defaults to empty string, meaning using the current route.

Method Details

__construct() method (available since v1.0.1)
public void __construct(integer $itemCount=0)
$itemCount integer total number of items.

Constructor.

applyLimit() method (available since v1.0.1)
public void applyLimit(CDbCriteria $criteria)
$criteria CDbCriteria the query criteria that should be applied with the limit

Applies LIMIT and OFFSET to the specified query criteria.

createPageUrl() method
public string createPageUrl(CController $controller, integer $page)
$controller | CController | the controller that will create the actual URL
$page | integer | the page that the URL should point to. This is a zero-based index.
{return} | string | the created URL

Creates the URL suitable for pagination. This method is mainly called by pagers when creating URLs used to perform pagination. The default implementation is to call the controller's createUrl method with the page information. You may override this method if your URL scheme is not the same as the one supported by the controller's createUrl method.

getCurrentPage() method
public integer getCurrentPage(boolean $recalculate=true)
$recalculate | boolean | whether to recalculate the current page based on the page size and item count.
{return} | integer | the zero-based index of the current page. Defaults to 0.

getItemCount() method
public integer getItemCount()
{return} integer total number of items. Defaults to 0.

getLimit() method (available since v1.1.0)
public integer getLimit()
{return} integer the limit of the data. This may be used to set the LIMIT value for a SQL statement for fetching the current page of data. This returns the same value as pageSize.

getOffset() method (available since v1.1.0)
public integer getOffset()
{return} integer the offset of the data. This may be used to set the OFFSET value for a SQL statement for fetching the current page of data.

getPageCount() method
public integer getPageCount()
{return} integer number of pages

getPageSize() method
public integer getPageSize()
{return} integer number of items in each page. Defaults to 10.

setCurrentPage() method
public void setCurrentPage(integer $value)
$value integer the zero-based index of the current page.

setItemCount() method
public void setItemCount(integer $value)
$value integer total number of items.

setPageSize() method
public void setPageSize(integer $value)
$value integer number of items in each page


CSort

Package | system.web
Inheritance | class CSort » CComponent
Since | 1.0.1
Version | $Id: CSort.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSort represents information relevant to sorting.

When data needs to be sorted according to one or several attributes, we can use CSort to represent the sorting information and generate appropriate hyperlinks that can lead to sort actions.

CSort is designed to be used together with CActiveRecord. When creating a CSort instance, you need to specify modelClass. You can use CSort to generate hyperlinks by calling link. You can also use CSort to modify a CDbCriteria instance by calling applyOrder so that it can cause the query results to be sorted according to the specified attributes.

In order to prevent SQL injection attacks, CSort ensures that only valid model attributes can be sorted. This is determined based on modelClass and attributes. When attributes is not set, all attributes belonging to modelClass can be sorted. When attributes is set, only those attributes declared in the property can be sorted.

By configuring attributes, one can perform more complex sorts that may consist of things like compound attributes (e.g. sort based on the combination of first name and last name of users).

The property attributes should be an array of key-value pairs, where the keys represent the attribute names, while the values represent the virtual attribute definitions. For more details, please check the documentation about attributes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes that are allowed to be sorted. | CSort
defaultOrder | string | the default order that should be applied to the query criteria when the current request does not specify any sort. | CSort
descTag | string | the tag appeared in the GET parameter that indicates the attribute should be sorted in descending order. | CSort
directions | array | Returns the currently requested sort information. | CSort
modelClass | string | the name of the model class whose attributes can be sorted. | CSort
multiSort | boolean | whether the sorting can be applied to multiple attributes simultaneously. | CSort
orderBy | string | the order-by columns represented by this sort object. | CSort
params | array | the additional GET parameters (name=>value) that should be used when generating sort URLs. | CSort
route | string | the route (controller ID and action ID) for generating the sorted contents. | CSort
separators | array | separators used in the generated URL. | CSort
sortVar | string | the name of the GET parameter that specifies which attributes to be sorted in which direction. | CSort

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CSort
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
applyOrder() | Modifies the query criteria by changing its CDbCriteria::order property. | CSort
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createUrl() | Creates a URL that can lead to generating sorted data. | CSort
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getDirection() | Returns the sort direction of the specified attribute in the current request. | CSort
getDirections() | Returns the currently requested sort information. | CSort
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOrderBy() |  | CSort
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
link() | Generates a hyperlink that can be clicked to cause sorting. | CSort
raiseEvent() | Raises an event. | CComponent
resolveAttribute() | Returns the real definition of an attribute given its name. | CSort
resolveLabel() | Resolves the attribute label for the specified attribute. | CSort

Protected Methods

Hide inherited methods

Method | Description | Defined By
createLink() | Creates a hyperlink based on the given label and URL. | CSort

Property Details

attributes property
public array $attributes;

list of attributes that are allowed to be sorted. For example, array('user_id','create_time') would specify that only 'user_id' and 'create_time' of the model modelClass can be sorted. By default, this property is an empty array, which means all attributes in modelClass are allowed to be sorted.

This property can also be used to specify complex sorting. To do so, a virtual attribute can be declared in terms of a key-value pair in the array. The key refers to the name of the virtual attribute that may appear in the sort request, while the value specifies the definition of the virtual attribute.

In the simple case, a key-value pair can be like 'user'=>'user_id' where 'user' is the name of the virtual attribute while 'user_id' means the virtual attribute is the 'user_id' attribute in the modelClass.

A more flexible way is to specify the key-value pair as

'user'=>array(
    'asc'=>'first_name, last_name',
    'desc'=>'first_name DESC, last_name DESC',
    'label'=>'Name'
)
where 'user' is the name of the virtual attribute that specifies the full name of user (a compound attribute consisting of first name and last name of user). In this case, we have to use an array to define the virtual attribute with three elements: 'asc', 'desc' and 'label'.

The above approach can also be used to declare virtual attributes that consist of relational attributes. For example,
'price'=>array(
    'asc'=>'item.price',
    'desc'=>'item.price DESC',
    'label'=>'Item Price'
)

Note, the attribute name should not contain '-' or '.' characters because they are used as separators.

defaultOrder property
public string $defaultOrder;

the default order that should be applied to the query criteria when the current request does not specify any sort. For example, 'create_time DESC', or 'name, create_time DESC'.

descTag property
public string $descTag;

the tag appeared in the GET parameter that indicates the attribute should be sorted in descending order. Defaults to 'desc'.

directions property read-only
public array getDirections()

Returns the currently requested sort information.

modelClass property
public string $modelClass;

the name of the model class whose attributes can be sorted. The model class must be a child class of CActiveRecord.

multiSort property
public boolean $multiSort;

whether the sorting can be applied to multiple attributes simultaneously. Defaults to false, which means each time the data can only be sorted by one attribute.

orderBy property read-only (available since v1.1.0)
public string getOrderBy()

the order-by columns represented by this sort object. This can be put in the ORDER BY clause of a SQL statement.

params property (available since v1.0.9)
public array $params;

the additional GET parameters (name=>value) that should be used when generating sort URLs. Defaults to null, meaning using the currently available GET parameters.

route property
public string $route;

the route (controller ID and action ID) for generating the sorted contents. Defaults to empty string, meaning using the currently requested route.

separators property
public array $separators;

separators used in the generated URL. This must be an array consisting of two elements. The first element specifies the character separating different attributes, while the second element specifies the character separating attribute name and the corresponding sort direction. Defaults to array('-','.').

sortVar property
public string $sortVar;

the name of the GET parameter that specifies which attributes to be sorted in which direction. Defaults to 'sort'.

Method Details

__construct() method
public void __construct(string $modelClass=NULL)
$modelClass string the class name of data models that need to be sorted. This should be a child class of CActiveRecord.

Constructor.

applyOrder() method
public void applyOrder(CDbCriteria $criteria)
$criteria CDbCriteria the query criteria

Modifies the query criteria by changing its CDbCriteria::order property. This method will use directions to determine which columns need to be sorted. They will be put in the ORDER BY clause. If the criteria already has non-empty CDbCriteria::order value, the new value will be appended to it.

createLink() method
protected string createLink(string $attribute, string $label, string $url, array $htmlOptions)
$attribute | string | the name of the attribute that this link is for
$label | string | the label of the hyperlink
$url | string | the URL
$htmlOptions | array | additional HTML options
{return} | string | the generated hyperlink

Creates a hyperlink based on the given label and URL. You may override this method to customize the link generation.

createUrl() method
public string createUrl(CController $controller, array $directions)
$controller | CController | the controller that will be used to create the URL.
$directions | array | the sort directions indexed by attribute names. The sort direction is true if the corresponding attribute should be sorted in descending order.
{return} | string | the URL for sorting

Creates a URL that can lead to generating sorted data.

getDirection() method
public mixed getDirection(string $attribute)
$attribute | string | the attribute name
{return} | mixed | the sort direction of the attribut. True if the attribute should be sorted in descending order, false if in ascending order, and null if the attribute doesn't need to be sorted.

Returns the sort direction of the specified attribute in the current request.

getDirections() method
public array getDirections()
{return} array sort directions indexed by attribute names. The sort direction is true if the corresponding attribute should be sorted in descending order.

Returns the currently requested sort information.

getOrderBy() method (available since v1.1.0)
public string getOrderBy()
{return} string the order-by columns represented by this sort object. This can be put in the ORDER BY clause of a SQL statement.

link() method
public string link(string $attribute, string $label=NULL, array $htmlOptions=array ( ))
$attribute | string | the attribute name. This must be the actual attribute name, not alias. If it is an attribute of a related AR object, the name should be prefixed with the relation name (e.g. 'author.name', where 'author' is the relation name).
$label | string | the link label. If null, the label will be determined according to the attribute (see resolveLabel).
$htmlOptions | array | additional HTML attributes for the hyperlink tag
{return} | string | the generated hyperlink

Generates a hyperlink that can be clicked to cause sorting.

resolveAttribute() method
public mixed resolveAttribute(string $attribute)
$attribute | string | the attribute name that the user requests to sort on
{return} | mixed | the attribute name or the virtual attribute definition. False if the attribute cannot be sorted.

Returns the real definition of an attribute given its name. The resolution is based on attributes and CActiveRecord::attributeNames. When attributes is an empty array, if the name refers to an attribute of modelClass, then the name is returned back. When attributes is not empty, if the name refers to an attribute declared in attributes, then the corresponding virtual attribute definition is returned. In all other cases, false is returned, meaning the name does not refer to a valid attribute.

resolveLabel() method
public string resolveLabel(string $attribute)
$attribute | string | the attribute name.
{return} | string | the attribute label

Resolves the attribute label for the specified attribute. This will invoke CActiveRecord::getAttributeLabel to determine what label to use. If the attribute refers to a virtual attribute declared in attributes, then the label given in the attributes will be returned instead.


CTheme

Package | system.web
Inheritance | class CTheme » CComponent
Since | 1.0
Version | $Id: CTheme.php 1678 2010-01-07 21:02:00Z qiang.xue $
CTheme represents an application theme.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the file path to the theme folder | CTheme
baseUrl | string | the relative URL to the theme folder (without ending slash) | CTheme
name | string | theme name | CTheme
skinPath | string | the path for widget skins. | CTheme
systemViewPath | string | the path for system views. | CTheme
viewPath | string | the path for controller views. | CTheme

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CTheme
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBasePath() |  | CTheme
getBaseUrl() |  | CTheme
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLayoutFile() | Finds the layout file for the specified controller's layout. | CTheme
getName() |  | CTheme
getSkinPath() |  | CTheme
getSystemViewPath() |  | CTheme
getViewFile() | Finds the view file for the specified controller's view. | CTheme
getViewPath() |  | CTheme
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Property Details

basePath property read-only
public string getBasePath()

the file path to the theme folder

baseUrl property read-only
public string getBaseUrl()

the relative URL to the theme folder (without ending slash)

name property read-only
public string getName()

theme name

skinPath property read-only (available since v1.1)
public string getSkinPath()

the path for widget skins. Defaults to 'ThemeRoot/views/skins'.

systemViewPath property read-only
public string getSystemViewPath()

the path for system views. Defaults to 'ThemeRoot/views/system'.

viewPath property read-only
public string getViewPath()

the path for controller views. Defaults to 'ThemeRoot/views'.

Method Details

__construct() method
public void __construct(string $name, string $basePath, string $baseUrl)
$name | string | name of the theme
$basePath | string | base theme path
$baseUrl | string | base theme URL

Constructor.

getBasePath() method
public string getBasePath()
{return} string the file path to the theme folder

getBaseUrl() method
public string getBaseUrl()
{return} string the relative URL to the theme folder (without ending slash)

getLayoutFile() method
public string getLayoutFile(CController $controller, string $layoutName)
$controller | CController | the controller
$layoutName | string | the layout name
{return} | string | the layout file path. False if the file does not exist.

Finds the layout file for the specified controller's layout.

getName() method
public string getName()
{return} string theme name

getSkinPath() method (available since v1.1)
public string getSkinPath()
{return} string the path for widget skins. Defaults to 'ThemeRoot/views/skins'.

getSystemViewPath() method
public string getSystemViewPath()
{return} string the path for system views. Defaults to 'ThemeRoot/views/system'.

getViewFile() method
public string getViewFile(CController $controller, string $viewName)
$controller | CController | the controller
$viewName | string | the view name
{return} | string | the view file path. False if the file does not exist.

Finds the view file for the specified controller's view.

getViewPath() method
public string getViewPath()
{return} string the path for controller views. Defaults to 'ThemeRoot/views'.


CThemeManager

Package | system.web
Inheritance | class CThemeManager » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CThemeManager.php 1832 2010-02-20 03:22:45Z qiang.xue $
CThemeManager manages the themes for the Web application.

A theme is a collection of view/layout files and resource files (e.g. css, image, js files). When a theme is active, CController will look for the specified view/layout under the theme folder first. The corresponding view/layout files will be used if the theme provides them. Otherwise, the default view/layout files will be used.

By default, each theme is organized as a directory whose name is the theme name. All themes are located under the "WebRootPath/themes" directory.

To activate a theme, set the theme property to be the name of that theme.

Since a self-contained theme often contains resource files that are made Web accessible, please make sure the view/layout files are protected from Web access.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the base path for all themes. | CThemeManager
baseUrl | string | the base URL for all themes. | CThemeManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
themeClass | string | the name of the theme class for representing a theme. | CThemeManager
themeNames | array | list of available theme names | CThemeManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBasePath() |  | CThemeManager
getBaseUrl() |  | CThemeManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getTheme() |  | CThemeManager
getThemeNames() |  | CThemeManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent
setBasePath() |  | CThemeManager
setBaseUrl() |  | CThemeManager

Property Details

basePath property
public string getBasePath()
public void setBasePath(string $value)

the base path for all themes. Defaults to "WebRootPath/themes".

baseUrl property
public string getBaseUrl()
public void setBaseUrl(string $value)

the base URL for all themes. Defaults to "/WebRoot/themes".

themeClass property
public string $themeClass;

the name of the theme class for representing a theme. Defaults to CTheme. This can also be a class name in dot syntax.

themeNames property read-only
public array getThemeNames()

list of available theme names

Method Details

getBasePath() method
public string getBasePath()
{return} string the base path for all themes. Defaults to "WebRootPath/themes".

getBaseUrl() method
public string getBaseUrl()
{return} string the base URL for all themes. Defaults to "/WebRoot/themes".

getTheme() method
public CTheme getTheme(string $name)
$name | string | name of the theme to be retrieved
{return} | CTheme | the theme retrieved. Null if the theme does not exist.

getThemeNames() method
public array getThemeNames()
{return} array list of available theme names

setBasePath() method
public void setBasePath(string $value)
$value string the base path for all themes.

setBaseUrl() method
public void setBaseUrl(string $value)
$value string the base URL for all themes.


CUploadedFile

Package | system.web
Inheritance | class CUploadedFile » CComponent
Since | 1.0
Version | $Id: CUploadedFile.php 1678 2010-01-07 21:02:00Z qiang.xue $
CUploadedFile represents the information for an uploaded file.

Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
error | integer | Returns an error code describing the status of this file uploading. | CUploadedFile
extensionName | string | the file extension name for name. | CUploadedFile
hasError | boolean | whether there is an error with the uploaded file. | CUploadedFile
name | string | the original name of the file being uploaded | CUploadedFile
size | integer | the actual size of the uploaded file in bytes | CUploadedFile
tempName | string | the path of the uploaded file on the server. | CUploadedFile
type | string | the MIME-type of the uploaded file (such as "image/gif"). | CUploadedFile

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__toString() | String output. | CUploadedFile
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getError() | Returns an error code describing the status of this file uploading. | CUploadedFile
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getExtensionName() |  | CUploadedFile
getHasError() |  | CUploadedFile
getInstance() | Returns an instance of the specified uploaded file. | CUploadedFile
getInstanceByName() | Returns an instance of the specified uploaded file. | CUploadedFile
getInstances() | Returns all uploaded files for the given model attribute. | CUploadedFile
getInstancesByName() | Returns an array of instances for the specified array name. | CUploadedFile
getName() |  | CUploadedFile
getSize() |  | CUploadedFile
getTempName() |  | CUploadedFile
getType() |  | CUploadedFile
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
saveAs() | Saves the uploaded file. | CUploadedFile

Protected Methods

Hide inherited methods

Method | Description | Defined By
__construct() | Constructor. | CUploadedFile
collectFilesRecursive() | Processes incoming files for getInstanceByName. | CUploadedFile
prefetchFiles() | Initially processes $_FILES superglobal for easier use. | CUploadedFile

Property Details

error property read-only
public integer getError()

Returns an error code describing the status of this file uploading.

See Also

  • http://www.php.net/manual/en/features.file-upload.errors.php
extensionName property read-only
public string getExtensionName()

the file extension name for name. The extension name does not include the dot character. An empty string is returned if name does not have an extension name.

hasError property read-only
public boolean getHasError()

whether there is an error with the uploaded file. Check error for detailed error code information.

name property read-only
public string getName()

the original name of the file being uploaded

size property read-only
public integer getSize()

the actual size of the uploaded file in bytes

tempName property read-only
public string getTempName()

the path of the uploaded file on the server. Note, this is a temporary file which will be automatically deleted by PHP after the current request is processed.

type property read-only
public string getType()

the MIME-type of the uploaded file (such as "image/gif"). Since this MIME type is not checked on the server side, do not take this value for granted. Instead, use CFileHelper::getMimeType to determine the exact MIME type.

Method Details

__construct() method
protected void __construct(string $name, string $tempName, string $type, integer $size, integer $error)
$name | string | the original name of the file being uploaded
$tempName | string | the path of the uploaded file on the server.
$type | string | the MIME-type of the uploaded file (such as "image/gif").
$size | integer | the actual size of the uploaded file in bytes
$error | integer | the error code

Constructor. Use getInstance to get an instance of an uploaded file.

__toString() method (available since v1.0.2)
public string __toString()
{return} string the string representation of the object

String output. This is PHP magic method that returns string representation of an object. The implementation here returns the uploaded file's name.

collectFilesRecursive() method
protected static void collectFilesRecursive(string $key, mixed $names, mixed $tmp_names, mixed $types, mixed $sizes, mixed $errors)
$key | string | key for identifiing uploaded file: class name and subarray indexes
$names | mixed | file names provided by PHP
$tmp_names | mixed | temporary file names provided by PHP
$types | mixed | filetypes provided by PHP
$sizes | mixed | file sizes provided by PHP
$errors | mixed | uploading issues provided by PHP

Processes incoming files for getInstanceByName.

getError() method
public integer getError()
{return} integer the error code

Returns an error code describing the status of this file uploading.

See Also

  • http://www.php.net/manual/en/features.file-upload.errors.php
getExtensionName() method
public string getExtensionName()
{return} string the file extension name for name. The extension name does not include the dot character. An empty string is returned if name does not have an extension name.

getHasError() method
public boolean getHasError()
{return} boolean whether there is an error with the uploaded file. Check error for detailed error code information.

getInstance() method
public static CUploadedFile getInstance(CModel $model, string $attribute)
$model | CModel | the model instance
$attribute | string | the attribute name. For tabular file uploading, this can be in the format of "[$i]attributeName", where $i stands for an integer index.
{return} | CUploadedFile | the instance of the uploaded file. Null is returned if no file is uploaded for the specified model attribute.

Returns an instance of the specified uploaded file. The file should be uploaded using CHtml::activeFileField.

See Also

  • getInstanceByName
getInstanceByName() method
public static CUploadedFile getInstanceByName(string $name)
$name | string | the name of the file input field.
{return} | CUploadedFile | the instance of the uploaded file. Null is returned if no file is uploaded for the specified name.

Returns an instance of the specified uploaded file. The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').

getInstances() method
public static array getInstances(CModel $model, string $attribute)
$model | CModel | the model instance
$attribute | string | the attribute name. For tabular file uploading, this can be in the format of "[$i]attributeName", where $i stands for an integer index.
{return} | array | array of CUploadedFile objects. Empty array is returned if no available file was found for the given attribute.

Returns all uploaded files for the given model attribute.

getInstancesByName() method
public static array getInstancesByName(string $name)
$name | string | the name of the array of files
{return} | array | the array of CUploadedFile objects. Empty array is returned if no adequate upload was found. Please note that this array will contain all files from all subarrays regardless how deeply nested they are.

Returns an array of instances for the specified array name.

If multiple files were uploaded and saved as 'Files[0]', 'Files[1]', 'Files[n]'..., you can have them all by passing 'Files' as array name.

getName() method
public string getName()
{return} string the original name of the file being uploaded

getSize() method
public integer getSize()
{return} integer the actual size of the uploaded file in bytes

getTempName() method
public string getTempName()
{return} string the path of the uploaded file on the server. Note, this is a temporary file which will be automatically deleted by PHP after the current request is processed.

getType() method
public string getType()
{return} string the MIME-type of the uploaded file (such as "image/gif"). Since this MIME type is not checked on the server side, do not take this value for granted. Instead, use CFileHelper::getMimeType to determine the exact MIME type.

prefetchFiles() method
protected static void prefetchFiles()

Initially processes $_FILES superglobal for easier use. Only for internal usage.

saveAs() method
public boolean saveAs(string $file, boolean $deleteTempFile=true)
$file | string | the file path used to save the uploaded file
$deleteTempFile | boolean | whether to delete the temporary file after saving. If true, you will not be able to save the uploaded file again in the current request.
{return} | boolean | true whether the file is saved successfully

Saves the uploaded file.


CUrlManager

Package | system.web
Inheritance | class CUrlManager » CApplicationComponent » CComponent
Implements | IApplicationComponent
Since | 1.0
Version | $Id: CUrlManager.php 1854 2010-03-03 13:10:50Z qiang.xue $
CUrlManager manages the URLs of Yii Web applications.

It provides URL construction (createUrl()) as well as parsing (parseUrl()) functionality.

URLs managed via CUrlManager can be in one of the following two formats, by setting urlFormat property:
  • 'path' format: /path/to/EntryScript.php/name1/value1/name2/value2...
  • 'get' format: /path/to/EntryScript.php?name1=value1&name2=value2...

When using 'path' format, CUrlManager uses a set of rules to:
  • parse the requested URL into a route ('ControllerID/ActionID') and GET parameters;
  • create URLs based on the given route and GET parameters.

A rule consists of a route and a pattern. The latter is used by CUrlManager to determine which rule is used for parsing/creating URLs. A pattern is meant to match the path info part of a URL. It may contain named parameters using the syntax '<ParamName:RegExp>'.

When parsing a URL, a matching rule will extract the named parameters from the path info and put them into the $_GET variable; when creating a URL, a matching rule will extract the named parameters from $_GET and put them into the path info part of the created URL.

If a pattern ends with '/*', it means additional GET parameters may be appended to the path info part of the URL; otherwise, the GET parameters can only appear in the query string part.

To specify URL rules, set the rules property as an array of rules (pattern=>route). For example,
array(
    'articles'=>'article/list',
    'article/<id:\d+>/*'=>'article/read',
)
Two rules are specified in the above:
  • The first rule says that if the user requests the URL '/path/to/index.php/articles', it should be treated as '/path/to/index.php/article/list'; and vice versa applies when constructing such a URL.
  • The second rule contains a named parameter 'id' which is specified using the <ParamName:RegExp> syntax. It says that if the user requests the URL '/path/to/index.php/article/13', it should be treated as '/path/to/index.php/article/read?id=13'; and vice versa applies when constructing such a URL.

Starting from version 1.0.5, the route part may contain references to named parameters defined in the pattern part. This allows a rule to be applied to different routes based on matching criteria. For example,
array(
     '<_c:(post|comment)>/<id:\d+>/<_a:(create|update|delete)>'=>'<_c>/<_a>',
     '<_c:(post|comment)>/<id:\d+>'=>'<_a>/view',
     '<_c:(post|comment)>s/*'=>'<_a>/list',
)
In the above, we use two named parameters '<_c>' and '<_a>' in the route part. The '<_c>' parameter matches either 'post' or 'comment', while the '<_a>' parameter matches an action ID.

Like normal rules, these rules can be used for both parsing and creating URLs. For example, using the rules above, the URL '/index.php/post/123/create' would be parsed as the route 'post/create' with GET parameter 'id' being 123. And given the route 'post/list' and GET parameter 'page' being 2, we should get a URL '/index.php/posts/page/2'.

Starting from version 1.0.11, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://admin.example.com/en/profile may be parsed into GET parameters user=admin and lang=en. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:
array(
    'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
)

CUrlManager is a default application component that may be accessed via CWebApplication::getUrlManager().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
appendParams | boolean | whether to append GET parameters to the path info part. | CUrlManager
baseUrl | string | the base URL of the application (the part after host name and before query string). | CUrlManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
cacheID | string | the ID of the cache application component that is used to cache the parsed URL rules. | CUrlManager
caseSensitive | boolean | whether routes are case-sensitive. | CUrlManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
matchValue | boolean | whether the GET parameter values should match the corresponding sub-patterns in a rule before using it to create a URL. | CUrlManager
routeVar | string | the GET variable name for route. | CUrlManager
rules | array | the URL rules (pattern=>route). | CUrlManager
showScriptName | boolean | whether to show entry script name in the constructed URL. | CUrlManager
urlFormat | string | the URL format. | CUrlManager
urlSuffix | string | the URL suffix used when in 'path' format. | CUrlManager
useStrictParsing | boolean | whether to enable strict URL parsing. | CUrlManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createPathInfo() | Creates a path info based on the given parameters. | CUrlManager
createUrl() | Constructs a URL. | CUrlManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBaseUrl() |  | CUrlManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getUrlFormat() |  | CUrlManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CUrlManager
parsePathInfo() | Parses a path info into URL segments and saves them to $_GET and $_REQUEST. | CUrlManager
parseUrl() | Parses the user request. | CUrlManager
raiseEvent() | Raises an event. | CComponent
removeUrlSuffix() | Removes the URL suffix from path info. | CUrlManager
setBaseUrl() | Sets the base URL of the application (the part after host name and before query string). | CUrlManager
setUrlFormat() |  | CUrlManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
createUrlDefault() | Contructs a URL based on default settings. | CUrlManager
createUrlRule() | Creates a URL rule instance. | CUrlManager
processRules() | Processes the URL rules. | CUrlManager

Property Details

appendParams property (available since v1.0.3)
public boolean $appendParams;

whether to append GET parameters to the path info part. Defaults to true. This property is only effective when urlFormat is 'path' and is mainly used when creating URLs. When it is true, GET parameters will be appended to the path info and separate from each other using slashes. If this is false, GET parameters will be in query part.

baseUrl property
public string getBaseUrl()
public void setBaseUrl(string $value)

the base URL of the application (the part after host name and before query string). If showScriptName is true, it will include the script name part. Otherwise, it will not, and the ending slashes are stripped off.

cacheID property (available since v1.0.3)
public string $cacheID;

the ID of the cache application component that is used to cache the parsed URL rules. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching URL rules.

caseSensitive property (available since v1.0.1)
public boolean $caseSensitive;

whether routes are case-sensitive. Defaults to true. By setting this to false, the route in the incoming request will be turned to lower case first before further processing. As a result, you should follow the convention that you use lower case when specifying controller mapping (CWebApplication::controllerMap) and action mapping (CController::actions). Also, the directory names for organizing controllers should be in lower case.

matchValue property (available since v1.1.0)
public boolean $matchValue;

whether the GET parameter values should match the corresponding sub-patterns in a rule before using it to create a URL. Defaults to false, meaning a rule will be used for creating a URL only if its route and parameter names match the given ones. If this property is set true, then the given parameter values must also match the corresponding parameter sub-patterns. Note that setting this property to true will degrade performance.

routeVar property
public string $routeVar;

the GET variable name for route. Defaults to 'r'.

rules property
public array $rules;

the URL rules (pattern=>route).

showScriptName property
public boolean $showScriptName;

whether to show entry script name in the constructed URL. Defaults to true.

urlFormat property
public string getUrlFormat()
public void setUrlFormat(string $value)

the URL format. Defaults to 'path'. Valid values include 'path' and 'get'. Please refer to the guide for more details about the difference between these two formats.

urlSuffix property
public string $urlSuffix;

the URL suffix used when in 'path' format. For example, ".html" can be used so that the URL looks like pointing to a static HTML page. Defaults to empty.

useStrictParsing property (available since v1.0.6)
public boolean $useStrictParsing;

whether to enable strict URL parsing. This property is only effective when urlFormat is 'path'. If it is set true, then an incoming URL must match one of the URL rules. Otherwise, it will be treated as an invalid request and trigger a 404 HTTP exception. Defaults to false.

Method Details

createPathInfo() method (available since v1.0.3)
public string createPathInfo(array $params, string $equal, string $ampersand, string $key=NULL)
$params | array | list of GET parameters
$equal | string | the separator between name and value
$ampersand | string | the separator between name-value pairs
$key | string | this is used internally.
{return} | string | the created path info

Creates a path info based on the given parameters.

createUrl() method
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$route | string | the controller and the action (e.g. article/read)
$params | array | list of GET parameters (name=>value). Both the name and value will be URL-encoded. If the name is '#', the corresponding value will be treated as an anchor and will be appended at the end of the URL. This anchor feature has been available since version 1.0.1.
$ampersand | string | the token separating name-value pairs in the URL. Defaults to '&'.
{return} | string | the constructed URL

Constructs a URL.

createUrlDefault() method
protected string createUrlDefault(string $route, array $params, string $ampersand)
$route | string | the controller and the action (e.g. article/read)
$params | array | list of GET parameters
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Contructs a URL based on default settings.

createUrlRule() method (available since v1.1.0)
protected CUrlRule createUrlRule(string $route, mixed $pattern)
$route | string | the pattern part of the rule
$pattern | mixed | the route part of the rule. This could be a string or an array
{return} | CUrlRule | the URL rule instance

Creates a URL rule instance. The default implementation returns a CUrlRule object.

getBaseUrl() method
public string getBaseUrl()
{return} string the base URL of the application (the part after host name and before query string). If showScriptName is true, it will include the script name part. Otherwise, it will not, and the ending slashes are stripped off.

getUrlFormat() method
public string getUrlFormat()
{return} string the URL format. Defaults to 'path'. Valid values include 'path' and 'get'. Please refer to the guide for more details about the difference between these two formats.

init() method
public void init()

Initializes the application component.

parsePathInfo() method (available since v1.0.3)
public void parsePathInfo(string $pathInfo)
$pathInfo string path info

Parses a path info into URL segments and saves them to $_GET and $_REQUEST.

parseUrl() method
public string parseUrl(CHttpRequest $request)
$request | CHttpRequest | the request application component
{return} | string | the route (controllerID/actionID) and perhaps GET parameters in path format.

Parses the user request.

processRules() method
protected void processRules()

Processes the URL rules.

removeUrlSuffix() method
public string removeUrlSuffix(string $pathInfo, string $urlSuffix)
$pathInfo | string | path info part in the URL
$urlSuffix | string | the URL suffix to be removed
{return} | string | path info with URL suffix removed.

Removes the URL suffix from path info.

setBaseUrl() method (available since v1.1.1)
public void setBaseUrl(string $value)
$value string the base URL of the application

Sets the base URL of the application (the part after host name and before query string). This method is provided in case the baseUrl cannot be determined automatically. The ending slashes should be stripped off. And you are also responsible to remove the script name if you set showScriptName to be false.

setUrlFormat() method
public void setUrlFormat(string $value)
$value string the URL format. It must be either 'path' or 'get'.


CUrlRule

Package | system.web
Inheritance | class CUrlRule » CComponent
Since | 1.0
Version | $Id: CUrlManager.php 1854 2010-03-03 13:10:50Z qiang.xue $
CUrlRule represents a URL formatting/parsing rule.

It mainly consists of two parts: route and pattern. The former classifies the rule so that it only applies to specific controller-action route. The latter performs the actual formatting and parsing role. The pattern may have a set of named parameters.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
append | boolean | whether the URL allows additional parameters at the end of the path info. | CUrlRule
caseSensitive | boolean | whether the rule is case sensitive. | CUrlRule
defaultParams | array | the default GET parameters (name=>value) that this rule provides. | CUrlRule
hasHostInfo | boolean | whether host info should be considered for this rule | CUrlRule
matchValue | boolean | whether the GET parameter values should match the corresponding sub-patterns in the rule when creating a URL. | CUrlRule
params | array | list of parameters (name=>regular expression) | CUrlRule
pattern | string | regular expression used to parse a URL | CUrlRule
references | array | the mapping from route param name to token name (e. | CUrlRule
route | string | the controller/action pair | CUrlRule
routePattern | string | the pattern used to match route | CUrlRule
template | string | template used to construct a URL | CUrlRule
urlSuffix | string | the URL suffix used for this rule. | CUrlRule

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CUrlRule
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createUrl() | Creates a URL based on this rule. | CUrlRule
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
parseUrl() | Parases a URL based on this rule. | CUrlRule
raiseEvent() | Raises an event. | CComponent

Property Details

append property
public boolean $append;

whether the URL allows additional parameters at the end of the path info.

caseSensitive property (available since v1.0.1)
public boolean $caseSensitive;

whether the rule is case sensitive. Defaults to null, meaning using the value of CUrlManager::caseSensitive.

defaultParams property (available since v1.0.8)
public array $defaultParams;

the default GET parameters (name=>value) that this rule provides. When this rule is used to parse the incoming request, the values declared in this property will be injected into $_GET.

hasHostInfo property (available since v1.0.11)
public boolean $hasHostInfo;

whether host info should be considered for this rule

matchValue property (available since v1.1.0)
public boolean $matchValue;

whether the GET parameter values should match the corresponding sub-patterns in the rule when creating a URL. Defaults to null, meaning using the value of CUrlManager::matchValue. When this property is false, it means a rule will be used for creating a URL if its route and parameter names match the given ones. If this property is set true, then the given parameter values must also match the corresponding parameter sub-patterns. Note that setting this property to true will degrade performance.

params property
public array $params;

list of parameters (name=>regular expression)

pattern property
public string $pattern;

regular expression used to parse a URL

references property (available since v1.0.5)
public array $references;

the mapping from route param name to token name (e.g. _r1=><1>)

route property
public string $route;

the controller/action pair

routePattern property (available since v1.0.5)
public string $routePattern;

the pattern used to match route

template property
public string $template;

template used to construct a URL

urlSuffix property (available since v1.0.6)
public string $urlSuffix;

the URL suffix used for this rule. For example, ".html" can be used so that the URL looks like pointing to a static HTML page. Defaults to null, meaning using the value of CUrlManager::urlSuffix.

Method Details

__construct() method
public void __construct(string $route, string $pattern)
$route | string | the route of the URL (controller/action)
$pattern | string | the pattern for matching the URL

Constructor.

createUrl() method
public string createUrl(CUrlManager $manager, string $route, array $params, string $ampersand)
$manager | CUrlManager | the manager
$route | string | the route
$params | array | list of parameters
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Creates a URL based on this rule.

parseUrl() method
public string parseUrl(CUrlManager $manager, CHttpRequest $request, string $pathInfo, string $rawPathInfo)
$manager | CUrlManager | the URL manager
$request | CHttpRequest | the request object
$pathInfo | string | path info part of the URL
$rawPathInfo | string | path info that contains the potential URL suffix
{return} | string | the route that consists of the controller ID and action ID

Parases a URL based on this rule.


CWebApplication

All Packages | Properties | Methods | Events
Package | system.web
Inheritance | class CWebApplication » CApplication » CModule » CComponent
Since | 1.0
Version | $Id: CWebApplication.php 1775 2010-02-01 20:02:44Z qiang.xue $
CWebApplication extends CApplication by providing functionalities specific to Web requests.

CWebApplication manages the controllers in MVC pattern, and provides the following additional core application components:
  • urlManager: provides URL parsing and constructing functionality;
  • request: encapsulates the Web request information;
  • session: provides the session-related functionalities;
  • assetManager: manages the publishing of private asset files.
  • user: represents the user session information.
  • themeManager: manages themes.
  • authManager: manages role-based access control (RBAC).
  • clientScript: manages client scripts (javascripts and CSS).

User requests are resolved as controller-action pairs and additional parameters. CWebApplication creates the requested controller instance and let it to handle the actual user request. If the user does not specify controller ID, it will assume defaultController is requested (which defaults to 'site').

Controller class files must reside under the directory controllerPath (defaults to 'protected/controllers'). The file name is the same as the controller name and the class name is the controller ID appended with 'Controller'. For example, the controller 'article' is defined by the class 'ArticleController' which is in the file 'protected/controller/article.php'.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
assetManager | CAssetManager | the asset manager component | CWebApplication
authManager | IAuthManager | the authorization manager component | CWebApplication
basePath | string | the root directory of the application. | CApplication
baseUrl | string | Returns the relative URL for the application. | CWebApplication
behaviors | array | the behaviors that should be attached to the module. | CModule
cache | CCache | the cache application component. | CApplication
catchAllRequest | array | the configuration specifying a controller which should handle all user requests. | CWebApplication
charset | string | the charset currently used for the application. | CApplication
clientScript | CClientScript | Returns the client script manager. | CWebApplication
components | array | the currently loaded components (indexed by their IDs) | CModule
controller | CController | the currently active controller | CWebApplication
controllerMap | array | mapping from controller ID to controller configurations. | CWebApplication
controllerPath | string | the directory that contains the controller classes. | CWebApplication
coreMessages | CPhpMessageSource | the core message translations | CApplication
dateFormatter | CDateFormatter | the locale-dependent date formatter. | CApplication
db | CDbConnection | the database connection | CApplication
defaultController | string | the ID of the default controller. | CWebApplication
errorHandler | CErrorHandler | the error handler application component. | CApplication
extensionPath | string | Returns the root directory that holds all third-party extensions. | CApplication
homeUrl | string | the homepage URL | CWebApplication
id | string | a unique identifier for the application. | CApplication
language | string | the language that the user is using and the application should be targeted to. | CApplication
layout | mixed | the application-wide layout. | CWebApplication
layoutPath | string | the root directory of layout files. | CWebApplication
locale | CLocale | the locale instance | CApplication
localeDataPath | string | the directory that contains the locale data. | CApplication
messages | CMessageSource | the application message translations | CApplication
modulePath | string | the directory that contains the application modules. | CModule
modules | array | the configuration of the currently installed modules (module ID => configuration) | CModule
name | string | the application name. | CApplication
numberFormatter | CNumberFormatter | the locale-dependent number formatter. | CApplication
params | CAttributeCollection | the list of user-defined parameters | CModule
parentModule | CModule | the parent module. | CModule
preload | array | the IDs of the application components that should be preloaded. | CModule
request | CHttpRequest | the request component | CApplication
runtimePath | string | the directory that stores runtime files. | CApplication
securityManager | CSecurityManager | the security manager application component. | CApplication
session | CHttpSession | the session component | CWebApplication
sourceLanguage | string | the language that the application is written in. | CApplication
statePersister | CStatePersister | the state persister application component. | CApplication
systemViewPath | string | the root directory of system view files. | CWebApplication
theme | CTheme | the theme used currently. | CWebApplication
themeManager | CThemeManager | the theme manager. | CWebApplication
timeZone | string | Returns the time zone used by this application. | CApplication
urlManager | CUrlManager | the URL manager component | CApplication
user | CWebUser | the user session information | CWebApplication
viewPath | string | the root directory of view files. | CWebApplication
viewRenderer | IViewRenderer | Returns the view renderer. | CWebApplication
widgetFactory | IWidgetFactory | Returns the widget factory. | CWebApplication

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CApplication
__get() | Getter magic method. | CModule
__isset() | Checks if a property value is null. | CModule
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
afterControllerAction() | The post-filter for controller actions. | CWebApplication
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beforeControllerAction() | The pre-filter for controller actions. | CWebApplication
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearGlobalState() | Clears a global value. | CApplication
configure() | Configures the module with the specified configuration. | CModule
createAbsoluteUrl() | Creates an absolute URL based on the given controller and action information. | CWebApplication
createController() | Creates a controller instance based on a route. | CWebApplication
createUrl() | Creates a relative URL based on the given controller and action information. | CWebApplication
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
displayError() | Displays the captured PHP error. | CApplication
displayException() | Displays the uncaught PHP exception. | CApplication
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
end() | Terminates the application. | CApplication
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
findLocalizedFile() | Returns the localized version of a specified file. | CApplication
findModule() | Searches for a module by its ID. | CWebApplication
getAssetManager() |  | CWebApplication
getAuthManager() |  | CWebApplication
getBasePath() |  | CApplication
getBaseUrl() | Returns the relative URL for the application. | CWebApplication
getCache() |  | CApplication
getClientScript() | Returns the client script manager. | CWebApplication
getComponent() | Retrieves the named application component. | CModule
getComponents() |  | CModule
getController() |  | CWebApplication
getControllerPath() |  | CWebApplication
getCoreMessages() |  | CApplication
getDateFormatter() |  | CApplication
getDb() |  | CApplication
getErrorHandler() |  | CApplication
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getExtensionPath() | Returns the root directory that holds all third-party extensions. | CApplication
getGlobalState() | Returns a global value. | CApplication
getHomeUrl() |  | CWebApplication
getId() |  | CApplication
getLanguage() |  | CApplication
getLayoutPath() |  | CWebApplication
getLocale() |  | CApplication
getLocaleDataPath() |  | CApplication
getMessages() |  | CApplication
getModule() | Retrieves the named application module. | CModule
getModulePath() |  | CModule
getModules() |  | CModule
getNumberFormatter() |  | CApplication
getParams() |  | CModule
getParentModule() |  | CModule
getRequest() |  | CApplication
getRuntimePath() |  | CApplication
getSecurityManager() |  | CApplication
getSession() |  | CWebApplication
getStatePersister() |  | CApplication
getSystemViewPath() |  | CWebApplication
getTheme() |  | CWebApplication
getThemeManager() |  | CWebApplication
getTimeZone() | Returns the time zone used by this application. | CApplication
getUrlManager() |  | CApplication
getUser() |  | CWebApplication
getViewPath() |  | CWebApplication
getViewRenderer() | Returns the view renderer. | CWebApplication
getWidgetFactory() | Returns the widget factory. | CWebApplication
handleError() | Handles PHP execution errors such as warnings, notices. | CApplication
handleException() | Handles uncaught PHP exceptions. | CApplication
hasComponent() |  | CModule
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
onBeginRequest() | Raised right BEFORE the application processes the request. | CApplication
onEndRequest() | Raised right AFTER the application processes the request. | CApplication
onError() | Raised when a PHP execution error occurs. | CApplication
onException() | Raised when an uncaught PHP exception occurs. | CApplication
processRequest() | Processes the current request. | CWebApplication
raiseEvent() | Raises an event. | CComponent
run() | Runs the application. | CApplication
runController() | Creates the controller and performs the specified action. | CWebApplication
setAliases() | Defines the root aliases. | CModule
setBasePath() | Sets the root directory of the application. | CApplication
setComponent() | Puts a component under the management of the module. | CModule
setComponents() | Sets the application components. | CModule
setController() |  | CWebApplication
setControllerPath() |  | CWebApplication
setExtensionPath() |  | CApplication
setGlobalState() | Sets a global value. | CApplication
setHomeUrl() |  | CWebApplication
setId() |  | CApplication
setImport() | Sets the aliases that are used in the module. | CModule
setLanguage() | Specifies which language the application is targeted to. | CApplication
setLayoutPath() |  | CWebApplication
setLocaleDataPath() |  | CApplication
setModulePath() |  | CModule
setModules() | Configures the sub-modules of this module. | CModule
setParams() |  | CModule
setRuntimePath() |  | CApplication
setSystemViewPath() |  | CWebApplication
setTheme() |  | CWebApplication
setTimeZone() | Sets the time zone used by this application. | CApplication
setViewPath() |  | CWebApplication

Protected Methods

Hide inherited methods

Method | Description | Defined By
init() | Initializes the application. | CWebApplication
initSystemHandlers() | Initializes the class autoloader and error handlers. | CApplication
loadGlobalState() | Loads the global state data from persistent storage. | CApplication
parseActionParams() | Parses a path info into an action ID and GET variables. | CWebApplication
preinit() | Preinitializes the module. | CModule
preloadComponents() | Loads static application components. | CModule
registerCoreComponents() | Registers the core application components. | CWebApplication
saveGlobalState() | Saves the global state data into persistent storage. | CApplication

Events

Hide inherited events

Event | Description | Defined By
onBeginRequest | Raised right BEFORE the application processes the request. | CApplication
onEndRequest | Raised right AFTER the application processes the request. | CApplication
onException | Raised when an uncaught PHP exception occurs. | CApplication
onError | Raised when a PHP execution error occurs. | CApplication

Property Details

assetManager property read-only
public CAssetManager getAssetManager()

the asset manager component

authManager property read-only
public IAuthManager getAuthManager()

the authorization manager component

baseUrl property read-only
public string getBaseUrl(boolean $absolute=false)

Returns the relative URL for the application. This is a shortcut method to CHttpRequest::getBaseUrl().

See Also

  • CHttpRequest::getBaseUrl()
catchAllRequest property
public array $catchAllRequest;

the configuration specifying a controller which should handle all user requests. This is mainly used when the application is in maintenance mode and we should use a controller to handle all incoming requests. The configuration specifies the controller route (the first element) and GET parameters (the rest name-value pairs). For example,

array(
    'offline/notice',
    'param1'=>'value1',
    'param2'=>'value2',
)
Defaults to null, meaning catch-all is not effective.

clientScript property read-only
public CClientScript getClientScript()

Returns the client script manager.

controller property
public CController getController()
public void setController(CController $value)

the currently active controller

controllerMap property
public array $controllerMap;

mapping from controller ID to controller configurations. Each name-value pair specifies the configuration for a single controller. A controller configuration can be either a string or an array. If the former, the string should be the class name or class path alias of the controller. If the latter, the array must contain a 'class' element which specifies the controller's class name or class path alias. The rest name-value pairs in the array are used to initialize the corresponding controller properties. For example,

array(
  'post'=>array(
     'class'=>'path.to.PostController',
     'pageTitle'=>'something new',
  ),
  'user'=>'path.to.UserController',,
)

Note, when processing an incoming request, the controller map will first be checked to see if the request can be handled by one of the controllers in the map. If not, a controller will be searched for under the default controller path.

controllerPath property
public string getControllerPath()
public void setControllerPath(string $value)

the directory that contains the controller classes. Defaults to 'protected/controllers'.

defaultController property
public string $defaultController;

the ID of the default controller. Defaults to 'site'.

homeUrl property
public string getHomeUrl()
public void setHomeUrl(string $value)

the homepage URL

layout property
public mixed $layout;

the application-wide layout. Defaults to 'main' (relative to layoutPath). If this is false, then no layout will be used.

layoutPath property
public string getLayoutPath()
public void setLayoutPath(string $path)

the root directory of layout files. Defaults to 'protected/views/layouts'.

session property read-only
public CHttpSession getSession()

the session component

systemViewPath property
public string getSystemViewPath()
public void setSystemViewPath(string $path)

the root directory of system view files. Defaults to 'protected/views/system'.

theme property
public CTheme getTheme()
public void setTheme(string $value)

the theme used currently. Null if no theme is being used.

themeManager property read-only
public CThemeManager getThemeManager()

the theme manager.

user property read-only
public CWebUser getUser()

the user session information

viewPath property
public string getViewPath()
public void setViewPath(string $path)

the root directory of view files. Defaults to 'protected/views'.

viewRenderer property read-only
public IViewRenderer getViewRenderer()

Returns the view renderer. If this component is registered and enabled, the default view rendering logic defined in CBaseController will be replaced by this renderer.

widgetFactory property read-only (available since v1.1)
public IWidgetFactory getWidgetFactory()

Returns the widget factory.

Method Details

afterControllerAction() method (available since v1.0.4)
public void afterControllerAction(CController $controller, CAction $action)
$controller | CController | the controller
$action | CAction | the action

The post-filter for controller actions. This method is invoked after the currently requested controller action and all its filters are executed. You may override this method with logic that needs to be done after all controller actions.

beforeControllerAction() method (available since v1.0.4)
public boolean beforeControllerAction(CController $controller, CAction $action)
$controller | CController | the controller
$action | CAction | the action
{return} | boolean | whether the action should be executed.

The pre-filter for controller actions. This method is invoked before the currently requested controller action and all its filters are executed. You may override this method with logic that needs to be done before all controller actions.

createAbsoluteUrl() method
public string createAbsoluteUrl(string $route, array $params=array ( ), string $schema='', string $ampersand='&')
$route | string | the URL route. This should be in the format of 'ControllerID/ActionID'.
$params | array | additional GET parameters (name=>value). Both the name and value will be URL-encoded.
$schema | string | schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Creates an absolute URL based on the given controller and action information.

createController() method
public array createController(string $route, CWebModule $owner=NULL)
$route | string | the route of the request.
$owner | CWebModule | the module that the new controller will belong to. Defaults to null, meaning the application instance is the owner.
{return} | array | the controller instance and the action ID. Null if the controller class does not exist or the route is invalid.

Creates a controller instance based on a route. The route should contain the controller ID and the action ID. It may also contain additional GET variables. All these must be concatenated together with slashes.

This method will attempt to create a controller in the following order:

  1. If the first segment is found in controllerMap, the corresponding controller configuration will be used to create the controller;
  2. If the first segment is found to be a module ID, the corresponding module will be used to create the controller;
  3. Otherwise, it will search under the controllerPath to create the corresponding controller. For example, if the route is "admin/user/create", then the controller will be created using the class file "protected/controllers/admin/UserController.php".

createUrl() method
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$route | string | the URL route. This should be in the format of 'ControllerID/ActionID'.
$params | array | additional GET parameters (name=>value). Both the name and value will be URL-encoded.
$ampersand | string | the token separating name-value pairs in the URL.
{return} | string | the constructed URL

Creates a relative URL based on the given controller and action information.

findModule() method (available since v1.0.3)
public CWebModule findModule(string $id)
$id | string | module ID
{return} | CWebModule | the module that has the specified ID. Null if no module is found.

Searches for a module by its ID. This method is used internally. Do not call this method.

getAssetManager() method
public CAssetManager getAssetManager()
{return} CAssetManager the asset manager component

getAuthManager() method
public IAuthManager getAuthManager()
{return} IAuthManager the authorization manager component

getBaseUrl() method
public string getBaseUrl(boolean $absolute=false)
$absolute | boolean | whether to return an absolute URL. Defaults to false, meaning returning a relative one. This parameter has been available since 1.0.2.
{return} | string | the relative URL for the application

Returns the relative URL for the application. This is a shortcut method to CHttpRequest::getBaseUrl().

See Also

  • CHttpRequest::getBaseUrl()
getClientScript() method
public CClientScript getClientScript()
{return} CClientScript the client script manager

Returns the client script manager.

getController() method
public CController getController()
{return} CController the currently active controller

getControllerPath() method
public string getControllerPath()
{return} string the directory that contains the controller classes. Defaults to 'protected/controllers'.

getHomeUrl() method
public string getHomeUrl()
{return} string the homepage URL

getLayoutPath() method
public string getLayoutPath()
{return} string the root directory of layout files. Defaults to 'protected/views/layouts'.

getSession() method
public CHttpSession getSession()
{return} CHttpSession the session component

getSystemViewPath() method
public string getSystemViewPath()
{return} string the root directory of system view files. Defaults to 'protected/views/system'.

getTheme() method
public CTheme getTheme()
{return} CTheme the theme used currently. Null if no theme is being used.

getThemeManager() method
public CThemeManager getThemeManager()
{return} CThemeManager the theme manager.

getUser() method
public CWebUser getUser()
{return} CWebUser the user session information

getViewPath() method
public string getViewPath()
{return} string the root directory of view files. Defaults to 'protected/views'.

getViewRenderer() method
public IViewRenderer getViewRenderer()
{return} IViewRenderer the view renderer.

Returns the view renderer. If this component is registered and enabled, the default view rendering logic defined in CBaseController will be replaced by this renderer.

getWidgetFactory() method (available since v1.1)
public IWidgetFactory getWidgetFactory()
{return} IWidgetFactory the widget factory

Returns the widget factory.

init() method
protected void init()

Initializes the application. This method overrides the parent implementation by preloading the 'request' component.

parseActionParams() method (available since v1.0.3)
protected string parseActionParams(string $pathInfo)
$pathInfo | string | path info
{return} | string | action ID

Parses a path info into an action ID and GET variables.

processRequest() method
public void processRequest()

Processes the current request. It first resolves the request into controller and action, and then creates the controller to perform the action.

registerCoreComponents() method
protected void registerCoreComponents()

Registers the core application components. This method overrides the parent implementation by registering additional core components.

See Also

  • setComponents
runController() method
public void runController(string $route)
$route string the route of the current request. See createController for more details.

Creates the controller and performs the specified action.

setController() method (available since v1.0.6)
public void setController(CController $value)
$value CController the currently active controller

setControllerPath() method
public void setControllerPath(string $value)
$value string the directory that contains the controller classes.

setHomeUrl() method
public void setHomeUrl(string $value)
$value string the homepage URL

setLayoutPath() method
public void setLayoutPath(string $path)
$path string the root directory of layout files.

setSystemViewPath() method
public void setSystemViewPath(string $path)
$path string the root directory of system view files.

setTheme() method
public void setTheme(string $value)
$value string the theme name

setViewPath() method
public void setViewPath(string $path)
$path string the root directory of view files.


CWebModule

Package | system.web
Inheritance | class CWebModule » CModule » CComponent
Since | 1.0.3
Version | $Id: CWebModule.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWebModule represents an application module.

An application module may be considered as a self-contained sub-application that has its own controllers, models and views and can be reused in a different project as a whole. Controllers inside a module must be accessed with routes that are prefixed with the module ID.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the root directory of the module. | CModule
behaviors | array | the behaviors that should be attached to the module. | CModule
components | array | the currently loaded components (indexed by their IDs) | CModule
controllerMap | array | mapping from controller ID to controller configurations. | CWebModule
controllerPath | string | the directory that contains the controller classes. | CWebModule
defaultController | string | the ID of the default controller for this module. | CWebModule
description | string | Returns the description of this module. | CWebModule
id | string | the module ID. | CModule
layout | mixed | the layout that is shared by the controllers inside this module. | CWebModule
layoutPath | string | the root directory of layout files. | CWebModule
modulePath | string | the directory that contains the application modules. | CModule
modules | array | the configuration of the currently installed modules (module ID => configuration) | CModule
name | string | Returns the name of this module. | CWebModule
params | CAttributeCollection | the list of user-defined parameters | CModule
parentModule | CModule | the parent module. | CModule
preload | array | the IDs of the application components that should be preloaded. | CModule
version | string | Returns the version of this module. | CWebModule
viewPath | string | the root directory of view files. | CWebModule

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CModule
__get() | Getter magic method. | CModule
__isset() | Checks if a property value is null. | CModule
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
afterControllerAction() | The post-filter for controller actions. | CWebModule
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beforeControllerAction() | The pre-filter for controller actions. | CWebModule
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures the module with the specified configuration. | CModule
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBasePath() |  | CModule
getComponent() | Retrieves the named application component. | CModule
getComponents() |  | CModule
getControllerPath() |  | CWebModule
getDescription() | Returns the description of this module. | CWebModule
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CModule
getLayoutPath() |  | CWebModule
getModule() | Retrieves the named application module. | CModule
getModulePath() |  | CModule
getModules() |  | CModule
getName() | Returns the name of this module. | CWebModule
getParams() |  | CModule
getParentModule() |  | CModule
getVersion() | Returns the version of this module. | CWebModule
getViewPath() |  | CWebModule
hasComponent() |  | CModule
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setAliases() | Defines the root aliases. | CModule
setBasePath() | Sets the root directory of the module. | CModule
setComponent() | Puts a component under the management of the module. | CModule
setComponents() | Sets the application components. | CModule
setControllerPath() |  | CWebModule
setId() |  | CModule
setImport() | Sets the aliases that are used in the module. | CModule
setLayoutPath() |  | CWebModule
setModulePath() |  | CModule
setModules() | Configures the sub-modules of this module. | CModule
setParams() |  | CModule
setViewPath() |  | CWebModule

Protected Methods

Hide inherited methods

Method | Description | Defined By
init() | Initializes the module. | CModule
preinit() | Preinitializes the module. | CModule
preloadComponents() | Loads static application components. | CModule

Property Details

controllerMap property
public array $controllerMap;

mapping from controller ID to controller configurations. Pleaser refer to CWebApplication::controllerMap for more details.

controllerPath property
public string getControllerPath()
public void setControllerPath(string $value)

the directory that contains the controller classes. Defaults to 'protected/controllers'.

defaultController property
public string $defaultController;

the ID of the default controller for this module. Defaults to 'default'.

description property read-only
public string getDescription()

Returns the description of this module. The default implementation returns an empty string. You may override this method to customize the description of this module.

layout property
public mixed $layout;

the layout that is shared by the controllers inside this module. If a controller has explicitly declared its own layout, this property will be ignored. If this is null (default), the application's layout or the parent module's layout (if available) will be used. If this is false, then no layout will be used.

layoutPath property
public string getLayoutPath()
public void setLayoutPath(string $path)

the root directory of layout files. Defaults to 'protected/views/layouts'.

name property read-only
public string getName()

Returns the name of this module. The default implementation simply returns id. You may override this method to customize the name of this module.

version property read-only
public string getVersion()

Returns the version of this module. The default implementation returns '1.0'. You may override this method to customize the version of this module.

viewPath property
public string getViewPath()
public void setViewPath(string $path)

the root directory of view files. Defaults to 'protected/views'.

Method Details

afterControllerAction() method (available since v1.0.4)
public void afterControllerAction(CController $controller, CAction $action)
$controller | CController | the controller
$action | CAction | the action

The post-filter for controller actions. This method is invoked after the currently requested controller action and all its filters are executed. If you override this method, make sure you call the parent implementation at the end.

beforeControllerAction() method (available since v1.0.4)
public boolean beforeControllerAction(CController $controller, CAction $action)
$controller | CController | the controller
$action | CAction | the action
{return} | boolean | whether the action should be executed.

The pre-filter for controller actions. This method is invoked before the currently requested controller action and all its filters are executed. You may override this method in the following way:

if(parent::beforeControllerAction($controller,$action))
{
    // your code
    return true;
}
else
    return false;

getControllerPath() method
public string getControllerPath()
{return} string the directory that contains the controller classes. Defaults to 'protected/controllers'.

getDescription() method
public string getDescription()
{return} string the description of this module.

Returns the description of this module. The default implementation returns an empty string. You may override this method to customize the description of this module.

getLayoutPath() method
public string getLayoutPath()
{return} string the root directory of layout files. Defaults to 'protected/views/layouts'.

getName() method
public string getName()
{return} string the name of this module.

Returns the name of this module. The default implementation simply returns id. You may override this method to customize the name of this module.

getVersion() method
public string getVersion()
{return} string the version of this module.

Returns the version of this module. The default implementation returns '1.0'. You may override this method to customize the version of this module.

getViewPath() method
public string getViewPath()
{return} string the root directory of view files. Defaults to 'protected/views'.

setControllerPath() method
public void setControllerPath(string $value)
$value string the directory that contains the controller classes.

setLayoutPath() method
public void setLayoutPath(string $path)
$path string the root directory of layout files.

setViewPath() method
public void setViewPath(string $path)
$path string the root directory of view files.


CWidgetFactory

Package | system.web
Inheritance | class CWidgetFactory » CApplicationComponent » CComponent
Implements | IApplicationComponent, IWidgetFactory
Since | 1.1
Version | $Id: CWidgetFactory.php 1746 2010-01-25 12:00:35Z qiang.xue $
CWidgetFactory creates new widgets to be used in views.

CWidgetFactory is used as the default "widgetFactory" application component.

When calling CBaseController::createWidget, CBaseController::widget or CBaseController::beginWidget, if the "widgetFactory" component is installed, it will be used to create the requested widget. To install the "widgetFactory" component, we should have the following application configuration:
return array(
    'components'=>array(
        'widgetFactory'=>array(
            'class'=>'CWidgetFactory',
        ),
    ),
)

CWidgetFactory implements the "skin" feature, which allows a new widget to be created and initialized with a set of predefined property values (called skin).

When CWidgetFactory is used to create a new widget, it will first instantiate the widget instance. It then checks if there is a skin available for this widget according to the widget class name and the widget CWidget::skin property. If a skin is found, it will be merged with the initial properties passed via createWidget. Then the merged initial properties will be used to initialize the newly created widget instance.

As aforementioned, a skin is a set of initial property values for a widget. It is thus represented as an associative array of name-value pairs. Skins are stored in PHP scripts like other configurations. Each script file stores the skins for a particular widget type and is named as the wiget class name (e.g. CLinkPager.php). Each widget type may have one or several skins, identified by the skin name set via CWidget::skin property. If the CWidget::skin property is not set for a given widget, it means the default skin would be used. The following shows the possible skins for the CLinkPager widget:
return array(
    'default'=>array(
        'nextPageLabel'=>'>>',
        'prevPageLabel'=>'<<',
    ),
    'short'=>array(
        'header'=>'',
        'maxButtonCount'=>5,
    ),
);
In the above, there are two skins. The first one is the default skin which is indexed by the string "default". Note that CWidget::skin defaults to "default". Therefore, this is the skin that will be applied if we do not explicitly specify the CWidget::skin property. The second one is named as the "short" skin which will be used only when we set CWidget::skin to be "short".

By default, CWidgetFactory looks for the skin of a widget under the "skins" directory of the current application's CWebApplication::viewPath (e.g. protected/views/skins). If a theme is being used, it will look for the skin under the "skins" directory of the theme's CTheme::viewPath (as well as the aforementioned skin directory). In case the specified skin is not found, a widget will still be created normally without causing any error.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
skinPath | string | the directory containing all the skin files. | CWidgetFactory
widgets | array | list of widget class names that can be skinned. | CWidgetFactory

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a new widget based on the given class name and initial properties. | CWidgetFactory
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CWidgetFactory
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
getSkin() | Returns the skin for the specified widget class and skin name. | CWidgetFactory

Property Details

skinPath property
public string $skinPath;

the directory containing all the skin files. Defaults to null, meaning using the "skin" directory under the current application's CWebApplication::viewPath.

widgets property
public array $widgets;

list of widget class names that can be skinned. Because skinning widgets has performance impact, you may want to specify this property to limit skinning only to specific widgets. Any widgets that are not in this list will not be skinned. Defaults to null, meaning all widgets can be skinned.

Method Details

createWidget() method
public CWidget createWidget(CBaseController $owner, string $className, array $properties=array ( ))
$owner | CBaseController | the owner of the new widget
$className | string | the class name of the widget. This can also be a path alias (e.g. system.web.widgets.COutputCache)
$properties | array | the initial property values (name=>value) of the widget.
{return} | CWidget | the newly created widget whose properties have been initialized with the given values.

Creates a new widget based on the given class name and initial properties.

getSkin() method
protected array getSkin(string $className, string $skinName)
$className | string | the widget class name
$skinName | string | the widget skin name
{return} | array | the skin (name=>value) for the widget

Returns the skin for the specified widget class and skin name.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by resolving the skin path.


IDataProvider

All Packages | Methods
Package | system.web
Inheritance | interface IDataProvider
Subclasses | CActiveDataProvider, CDataProvider
Since | 1.1
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IDataProvider is the interface that must be implemented by data provider classes.

Data providers are components that can feed data for widgets such as data grid, data list. Besides providing data, they also support pagination and sorting.

Public Methods

Hide inherited methods

Method | Description | Defined By
getData() | Returns the data items currently available. | IDataProvider
getId() |  | IDataProvider
getItemCount() | Returns the number of data items in the current page. | IDataProvider
getKeys() | Returns the key values associated with the data items. | IDataProvider
getPagination() |  | IDataProvider
getSort() |  | IDataProvider
getTotalItemCount() | Returns the total number of data items. | IDataProvider

Method Details

getData() method
abstract public array getData(boolean $refresh=false)
$refresh | boolean | whether the data should be re-fetched from persistent storage.
{return} | array | the list of data items currently available in this data provider.

Returns the data items currently available.

getId() method
abstract public string getId()
{return} string the unique ID that identifies the data provider from other data providers.

getItemCount() method
abstract public integer getItemCount(boolean $refresh=false)
$refresh | boolean | whether the number of data items should be re-calculated.
{return} | integer | the number of data items in the current page.

Returns the number of data items in the current page. This is equivalent to count($provider->getData()). When pagination is set false, this returns the same value as totalItemCount.

getKeys() method
abstract public array getKeys(boolean $refresh=false)
$refresh | boolean | whether the keys should be re-calculated.
{return} | array | the list of key values corresponding to data. Each data item in data is uniquely identified by the corresponding key value in this array.

Returns the key values associated with the data items.

getPagination() method
abstract public CPagination getPagination()
{return} CPagination the pagination object. If this is false, it means the pagination is disabled.

getSort() method
abstract public CSort getSort()
{return} CSort the sorting object. If this is false, it means the sorting is disabled.

getTotalItemCount() method
abstract public integer getTotalItemCount(boolean $refresh=false)
$refresh | boolean | whether the total number of data items should be re-calculated.
{return} | integer | total number of possible data items.

Returns the total number of data items. When pagination is set false, this returns the same value as itemCount.


IWidgetFactory

All Packages | Methods
Package | system.web
Inheritance | interface IWidgetFactory
Subclasses | CWidgetFactory
Since | 1.1
Version | $Id: interfaces.php 1678 2010-01-07 21:02:00Z qiang.xue $
IWidgetFactory is the interface that must be implemented by a widget factory class.

When calling CBaseController::createWidget, if a widget factory is available, it will be used for creating the requested widget.

Public Methods

Hide inherited methods

Method | Description | Defined By
createWidget() | Creates a new widget based on the given class name and initial properties. | IWidgetFactory

Method Details

createWidget() method
abstract public CWidget createWidget(CBaseController $owner, string $className, array $properties=array ( ))
$owner | CBaseController | the owner of the new widget
$className | string | the class name of the widget. This can also be a path alias (e.g. system.web.widgets.COutputCache)
$properties | array | the initial property values (name=>value) of the widget.
{return} | CWidget | the newly created widget whose properties have been initialized with the given values.

Creates a new widget based on the given class name and initial properties.


CAction

Package | system.web.actions
Inheritance | abstract class CAction » CComponent
Implements | IAction
Subclasses | CCaptchaAction, CInlineAction, CViewAction, CWebServiceAction
Since | 1.0
Version | $Id: CAction.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAction is the base class for all controller action classes.

CAction provides a way to divide a complex controller into smaller actions in separate class files.

Derived classes must implement run() which is invoked by controller when the action is requested.

An action instance can access its controller via controller property.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
controller | CController | the controller who owns this action. | CAction
id | string | id of this action | CAction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CAction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CAction
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
run() | Runs the action. | IAction

Property Details

controller property read-only
public CController getController()

the controller who owns this action.

id property read-only
public string getId()

id of this action

Method Details

__construct() method
public void __construct(CController $controller, string $id)
$controller | CController | the controller who owns this action.
$id | string | id of the action.

Constructor.

getController() method
public CController getController()
{return} CController the controller who owns this action.

getId() method
public string getId()
{return} string id of this action


CInlineAction

Package | system.web.actions
Inheritance | class CInlineAction » CAction » CComponent
Implements | IAction
Since | 1.0
Version | $Id: CInlineAction.php 1678 2010-01-07 21:02:00Z qiang.xue $
CInlineAction represents an action that is defined as a controller method.

The method name is like 'actionXYZ' where 'XYZ' stands for the action name.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
controller | CController | the controller who owns this action. | CAction
id | string | id of this action | CAction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CAction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CAction
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
run() | Runs the action. | CInlineAction

Method Details

run() method
public void run()

Runs the action. The action method defined in the controller is invoked. This method is required by CAction.


CViewAction

All Packages | Properties | Methods | Events
Package | system.web.actions
Inheritance | class CViewAction » CAction » CComponent
Implements | IAction
Since | 1.0
Version | $Id: CViewAction.php 1828 2010-02-20 00:51:38Z qiang.xue $
CViewAction represents an action that displays a view according to a user-specified parameter.

By default, the view being displayed is specified via the view GET parameter. The name of the GET parameter can be customized via viewParam. If the user doesn't provide the GET parameter, the default view specified by defaultView will be displayed.

Users specify a view in the format of path.to.view, which translates to the view name BasePath/path/to/view where BasePath is given by basePath.

Note, the user specified view can only contain word characters, dots and dashes and the first letter must be a word letter.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
basePath | string | the base path for the views. | CViewAction
controller | CController | the controller who owns this action. | CAction
defaultView | string | the name of the default view when viewParam GET parameter is not provided by user. | CViewAction
id | string | id of this action | CAction
layout | mixed | the name of the layout to be applied to the views. | CViewAction
renderAsText | boolean | whether the view should be rendered as PHP script or static text. | CViewAction
requestedView | string | Returns the name of the view requested by the user. | CViewAction
view | string | the name of the view to be rendered. | CViewAction
viewParam | string | the name of the GET parameter that contains the requested view name. | CViewAction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CAction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CAction
getRequestedView() | Returns the name of the view requested by the user. | CViewAction
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
onAfterRender() | Raised right after the action invokes the render method. | CViewAction
onBeforeRender() | Raised right before the action invokes the render method. | CViewAction
raiseEvent() | Raises an event. | CComponent
run() | Runs the action. | CViewAction

Protected Methods

Hide inherited methods

Method | Description | Defined By
resolveView() | Resolves the user-specified view into a valid view name. | CViewAction

Events

Hide inherited events

Event | Description | Defined By
onBeforeRender | Raised right before the action invokes the render method. | CViewAction
onAfterRender | Raised right after the action invokes the render method. | CViewAction

Property Details

basePath property
public string $basePath;

the base path for the views. Defaults to 'pages'. The base path will be prefixed to any user-specified page view. For example, if a user requests for tutorial.chap1, the corresponding view name will be pages/tutorial/chap1, assuming the base path is pages. The actual view file is determined by CController::getViewFile.

See Also

  • CController::getViewFile
defaultView property
public string $defaultView;

the name of the default view when viewParam GET parameter is not provided by user. Defaults to 'index'. This should be in the format of 'path.to.view', similar to that given in the GET parameter.

See Also

  • basePath
layout property
public mixed $layout;

the name of the layout to be applied to the views. This will be assigned to CController::layout before the view is rendered. Defaults to null, meaning the controller's layout will be used. If false, no layout will be applied.

renderAsText property
public boolean $renderAsText;

whether the view should be rendered as PHP script or static text. Defaults to false.

requestedView property read-only
public string getRequestedView()

Returns the name of the view requested by the user. If the user doesn't specify any view, the defaultView will be returned.

view property
public string $view;

the name of the view to be rendered. This property will be set once the user requested view is resolved.

viewParam property
public string $viewParam;

the name of the GET parameter that contains the requested view name. Defaults to 'view'.

Method Details

getRequestedView() method
public string getRequestedView()
{return} string the name of the view requested by the user. This is in the format of 'path.to.view'.

Returns the name of the view requested by the user. If the user doesn't specify any view, the defaultView will be returned.

onAfterRender() method
public void onAfterRender(CEvent $event)
$event CEvent event parameter

Raised right after the action invokes the render method.

onBeforeRender() method
public void onBeforeRender(CEvent $event)
$event CEvent event parameter

Raised right before the action invokes the render method. Event handlers can set the CEvent::handled property to be true to stop further view rendering.

resolveView() method
protected string resolveView(string $viewPath)
$viewPath | string | user-specified view in the format of 'path.to.view'.
{return} | string | fully resolved view in the format of 'path/to/view'.

Resolves the user-specified view into a valid view name.

run() method
public void run()

Runs the action. This method displays the view requested by the user.


CAccessControlFilter

Package | system.web.auth
Inheritance | class CAccessControlFilter » CFilter » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CAccessControlFilter.php 1782 2010-02-01 21:05:25Z qiang.xue $
CAccessControlFilter performs authorization checks for the specified actions.

By enabling this filter, controller actions can be checked for access permissions. Only when the user is allowed by one of the security rules, will he be able to access the action.

To specify the access rules, set the rules property, which should be an array of the rules. Each rule is specified as an array of the following structure:
array(
  'allow',  // or 'deny'
  // optional, list of action IDs (case insensitive) that this rule applies to
  'actions'=>array('edit', 'delete'),
  // optional, list of controller IDs (case insensitive) that this rule applies to
  // This option is available since version 1.0.3.
  'controllers'=>array('post', 'admin/user'),
  // optional, list of usernames (case insensitive) that this rule applies to
  // Use * to represent all users, ? guest users, and @ authenticated users
  'users'=>array('thomas', 'kevin'),
  // optional, list of roles (case sensitive!) that this rule applies to.
  'roles'=>array('admin', 'editor'),
  // optional, list of IP address/patterns that this rule applies to
  // e.g. 127.0.0.1, 127.0.0.*
  'ips'=>array('127.0.0.1'),
  // optional, list of request types (case insensitive) that this rule applies to
  'verbs'=>array('GET', 'POST'),
  // optional, a PHP expression whose value indicates whether this rule applies
  // This option is available since version 1.0.3.
  'expression'=>'!$user->isGuest && $user->level==2',
  // optional, the customized error message to be displayed
  // This option is available since version 1.1.1.
  'message'=>'Access Denied.',
)

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
message | string | the error message to be displayed when authorization fails. | CAccessControlFilter
rules | array | list of access rules. | CAccessControlFilter

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getRules() |  | CAccessControlFilter
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setRules() |  | CAccessControlFilter

Protected Methods

Hide inherited methods

Method | Description | Defined By
accessDenied() | Denies the access of the user. | CAccessControlFilter
postFilter() | Performs the post-action filtering. | CFilter
preFilter() | Performs the pre-action filtering. | CAccessControlFilter
resolveErrorMessage() | Resolves the error message to be displayed. | CAccessControlFilter

Property Details

message property (available since v1.1.1)
public string $message;

the error message to be displayed when authorization fails. This property can be overridden by individual access rule via CAccessRule::message. If this property is not set, a default error message will be displayed.

rules property
public array getRules()
public void setRules(array $rules)

list of access rules.

Method Details

accessDenied() method (available since v1.0.5)
protected void accessDenied(IWebUser $user, string $message)
$user | IWebUser | the current user
$message | string | the error message to be displayed

Denies the access of the user. This method is invoked when access check fails.

getRules() method
public array getRules()
{return} array list of access rules.

preFilter() method
protected boolean preFilter(CFilterChain $filterChain)
$filterChain | CFilterChain | the filter chain that the filter is on.
{return} | boolean | whether the filtering process should continue and the action should be executed.

Performs the pre-action filtering.

resolveErrorMessage() method (available since v1.1.1)
protected string resolveErrorMessage(CAccessRule $rule)
$rule | CAccessRule | the access rule
{return} | string | the error message

Resolves the error message to be displayed. This method will check message and CAccessRule::message to see what error message should be displayed.

setRules() method
public void setRules(array $rules)
$rules array list of access rules.


CAccessRule

Package | system.web.auth
Inheritance | class CAccessRule » CComponent
Since | 1.0
Version | $Id: CAccessControlFilter.php 1782 2010-02-01 21:05:25Z qiang.xue $
CAccessRule represents an access rule that is managed by CAccessControlFilter.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actions | array | list of action IDs that this rule applies to. | CAccessRule
allow | boolean | whether this is an 'allow' rule or 'deny' rule. | CAccessRule
controllers | array | list of controler IDs that this rule applies to. | CAccessRule
expression | string | a PHP expression whose value indicates whether this rule should be applied. | CAccessRule
ips | array | IP patterns. | CAccessRule
message | string | the error message to be displayed when authorization is denied by this rule. | CAccessRule
roles | array | list of roles this rule applies to. | CAccessRule
users | array | list of user names that this rule applies to. | CAccessRule
verbs | array | list of request types (e. | CAccessRule

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
isUserAllowed() | Checks whether the Web user is allowed to perform the specified action. | CAccessRule
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
isActionMatched() |  | CAccessRule
isControllerMatched() |  | CAccessRule
isExpressionMatched() |  | CAccessRule
isIpMatched() |  | CAccessRule
isRoleMatched() |  | CAccessRule
isUserMatched() |  | CAccessRule
isVerbMatched() |  | CAccessRule

Property Details

actions property
public array $actions;

list of action IDs that this rule applies to. The comparison is case-insensitive.

allow property
public boolean $allow;

whether this is an 'allow' rule or 'deny' rule.

controllers property (available since v1.0.4)
public array $controllers;

list of controler IDs that this rule applies to. The comparison is case-insensitive.

expression property (available since v1.0.3)
public string $expression;

a PHP expression whose value indicates whether this rule should be applied. In this expression, you can use $user which refers to Yii::app()->user. Starting from version 1.0.11, the expression can also be a valid PHP callback, including class method name (array(ClassName/Object, MethodName)), or anonymous function (PHP 5.3.0+). The function/method signature should be as follows:

function foo($user, $rule) { ... }
where $user is the current application user object and $rule is this access rule.

ips property
public array $ips;

IP patterns.

message property (available since v1.1.1)
public string $message;

the error message to be displayed when authorization is denied by this rule. If not set, a default error message will be displayed.

roles property
public array $roles;

list of roles this rule applies to. For each role, the current user's CWebUser::checkAccess method will be invoked. If one of the invocations returns true, the rule will be applied. Note, you should mainly use roles in an "allow" rule because by definition, a role represents a permission collection.

See Also

  • CAuthManager
users property
public array $users;

list of user names that this rule applies to. The comparison is case-insensitive.

verbs property
public array $verbs;

list of request types (e.g. GET, POST) that this rule applies to.

Method Details

isActionMatched() method
protected boolean isActionMatched(CAction $action)
$action | CAction | the action
{return} | boolean | whether the rule applies to the action

isControllerMatched() method
protected boolean isControllerMatched(CAction $controller)
$controller | CAction | the action
{return} | boolean | whether the rule applies to the action

isExpressionMatched() method (available since v1.0.3)
protected boolean isExpressionMatched(IWebUser $user)
$user | IWebUser | the user
{return} | boolean | the expression value. True if the expression is not specified.

isIpMatched() method
protected boolean isIpMatched(string $ip)
$ip | string | the IP address
{return} | boolean | whether the rule applies to the IP address

isRoleMatched() method
protected boolean isRoleMatched(string $user)
$user | string | the role name
{return} | boolean | whether the rule applies to the role

isUserAllowed() method
public integer isUserAllowed(CWebUser $user, CController $controller, CAction $action, string $ip, string $verb)
$user | CWebUser | the user object
$controller | CController | the controller currently being executed
$action | CAction | the action to be performed
$ip | string | the request IP address
$verb | string | the request verb (GET, POST, etc.)
{return} | integer | 1 if the user is allowed, -1 if the user is denied, 0 if the rule does not apply to the user

Checks whether the Web user is allowed to perform the specified action.

isUserMatched() method
protected boolean isUserMatched(IWebUser $user)
$user | IWebUser | the user
{return} | boolean | whether the rule applies to the user

isVerbMatched() method
protected boolean isVerbMatched(string $verb)
$verb | string | the request method
{return} | boolean | whether the rule applies to the request


CAuthAssignment

Package | system.web.auth
Inheritance | class CAuthAssignment » CComponent
Since | 1.0
Version | $Id: CAuthAssignment.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAuthAssignment represents an assignment of a role to a user. It includes additional assignment information such as bizRule and data. Do not create a CAuthAssignment instance using the 'new' operator. Instead, call IAuthManager::assign.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
bizRule | string | the business rule associated with this assignment | CAuthAssignment
data | mixed | additional data for this assignment | CAuthAssignment
itemName | string | the authorization item name | CAuthAssignment
userId | mixed | user ID (see IWebUser::getId) | CAuthAssignment

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAuthAssignment
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getBizRule() |  | CAuthAssignment
getData() |  | CAuthAssignment
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getItemName() |  | CAuthAssignment
getUserId() |  | CAuthAssignment
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setBizRule() |  | CAuthAssignment
setData() |  | CAuthAssignment

Property Details

bizRule property
public string getBizRule()
public void setBizRule(string $value)

the business rule associated with this assignment

data property
public mixed getData()
public void setData(mixed $value)

additional data for this assignment

itemName property read-only
public string getItemName()

the authorization item name

userId property read-only
public mixed getUserId()

user ID (see IWebUser::getId)

Method Details

__construct() method
public void __construct(IAuthManager $auth, string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$auth | IAuthManager | the authorization manager
$itemName | string | authorization item name
$userId | mixed | user ID (see IWebUser::getId)
$bizRule | string | the business rule associated with this assignment
$data | mixed | additional data for this assignment

Constructor.

getBizRule() method
public string getBizRule()
{return} string the business rule associated with this assignment

getData() method
public mixed getData()
{return} mixed additional data for this assignment

getItemName() method
public string getItemName()
{return} string the authorization item name

getUserId() method
public mixed getUserId()
{return} mixed user ID (see IWebUser::getId)

setBizRule() method
public void setBizRule(string $value)
$value string the business rule associated with this assignment

setData() method
public void setData(mixed $value)
$value mixed additional data for this assignment


CAuthItem

Package | system.web.auth
Inheritance | class CAuthItem » CComponent
Since | 1.0
Version | $Id: CAuthItem.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAuthItem represents an authorization item. An authorization item can be an operation, a task or a role. They form an authorization hierarchy. Items on higher levels of the hierarchy inherit the permissions represented by items on lower levels. A user may be assigned one or several authorization items (called assignments. He can perform an operation only when it is among his assigned items.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
authManager | IAuthManager | the authorization manager | CAuthItem
bizRule | string | the business rule associated with this item | CAuthItem
children | array | Returns the children of this item. | CAuthItem
data | string | the additional data associated with this item | CAuthItem
description | string | the item description | CAuthItem
name | string | the item name | CAuthItem
type | integer | the authorization item type. | CAuthItem

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAuthItem
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addChild() | Adds a child item. | CAuthItem
asa() | Returns the named behavior object. | CComponent
assign() | Assigns this item to a user. | CAuthItem
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkAccess() | Checks to see if the specified item is within the hierarchy starting from this item. | CAuthItem
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getAssignment() | Returns the item assignment information. | CAuthItem
getAuthManager() |  | CAuthItem
getBizRule() |  | CAuthItem
getChildren() | Returns the children of this item. | CAuthItem
getData() |  | CAuthItem
getDescription() |  | CAuthItem
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getName() |  | CAuthItem
getType() |  | CAuthItem
hasChild() | Returns a value indicating whether a child exists | CAuthItem
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
isAssigned() | Returns a value indicating whether this item has been assigned to the user. | CAuthItem
raiseEvent() | Raises an event. | CComponent
removeChild() | Removes a child item. | CAuthItem
revoke() | Revokes an authorization assignment from a user. | CAuthItem
setBizRule() |  | CAuthItem
setData() |  | CAuthItem
setDescription() |  | CAuthItem
setName() |  | CAuthItem

Property Details

authManager property read-only
public IAuthManager getAuthManager()

the authorization manager

bizRule property
public string getBizRule()
public void setBizRule(string $value)

the business rule associated with this item

children property read-only
public array getChildren()

Returns the children of this item.

See Also

  • IAuthManager::getItemChildren
data property
public string getData()
public void setData(string $value)

the additional data associated with this item

description property
public string getDescription()
public void setDescription(string $value)

the item description

name property
public string getName()
public void setName(string $value)

the item name

type property read-only
public integer getType()

the authorization item type. This could be 0 (operation), 1 (task) or 2 (role).

Method Details

__construct() method
public void __construct(IAuthManager $auth, string $name, integer $type, description $description='', string $bizRule=NULL, mixed $data=NULL)
$auth | IAuthManager | authorization manager
$name | string | authorization item name
$type | integer | authorization item type. This can be 0 (operation), 1 (task) or 2 (role).
$description | description | the description
$bizRule | string | the business rule associated with this item
$data | mixed | additional data for this item

Constructor.

addChild() method
public boolean addChild(string $name)
$name | string | the name of the child item
{return} | boolean | whether the item is added successfully

Adds a child item.

See Also

  • IAuthManager::addItemChild
assign() method
public CAuthAssignment assign(mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$userId | mixed | the user ID (see IWebUser::getId)
$bizRule | string | the business rule to be executed when checkAccess is called for this particular authorization item.
$data | mixed | additional data associated with this assignment
{return} | CAuthAssignment | the authorization assignment information.

Assigns this item to a user.

See Also

  • IAuthManager::assign
checkAccess() method
public boolean checkAccess(string $itemName, array $params=array ( ))
$itemName | string | the name of the item to be checked
$params | array | the parameters to be passed to business rule evaluation
{return} | boolean | whether the specified item is within the hierarchy starting from this item.

Checks to see if the specified item is within the hierarchy starting from this item. This method is internally used by IAuthManager::checkAccess.

getAssignment() method
public CAuthAssignment getAssignment(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | CAuthAssignment | the item assignment information. Null is returned if this item is not assigned to the user.

Returns the item assignment information.

See Also

  • IAuthManager::getAuthAssignment
getAuthManager() method
public IAuthManager getAuthManager()
{return} IAuthManager the authorization manager

getBizRule() method
public string getBizRule()
{return} string the business rule associated with this item

getChildren() method
public array getChildren()
{return} array all child items of this item.

Returns the children of this item.

See Also

  • IAuthManager::getItemChildren
getData() method
public string getData()
{return} string the additional data associated with this item

getDescription() method
public string getDescription()
{return} string the item description

getName() method
public string getName()
{return} string the item name

getType() method
public integer getType()
{return} integer the authorization item type. This could be 0 (operation), 1 (task) or 2 (role).

hasChild() method
public boolean hasChild(string $name)
$name | string | the child item name
{return} | boolean | whether the child exists

Returns a value indicating whether a child exists

See Also

  • IAuthManager::hasItemChild
isAssigned() method
public boolean isAssigned(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether the item has been assigned to the user.

Returns a value indicating whether this item has been assigned to the user.

See Also

  • IAuthManager::isAssigned
removeChild() method
public boolean removeChild(string $name)
$name | string | the child item name
{return} | boolean | whether the removal is successful

Removes a child item. Note, the child item is not deleted. Only the parent-child relationship is removed.

See Also

  • IAuthManager::removeItemChild
revoke() method
public boolean revoke(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether removal is successful

Revokes an authorization assignment from a user.

See Also

  • IAuthManager::revoke
setBizRule() method
public void setBizRule(string $value)
$value string the business rule associated with this item

setData() method
public void setData(string $value)
$value string the business rule associated with this item

setDescription() method
public void setDescription(string $value)
$value string the item description

setName() method
public void setName(string $value)
$value string the item name


CAuthManager

Package | system.web.auth
Inheritance | abstract class CAuthManager » CApplicationComponent » CComponent
Implements | IApplicationComponent, IAuthManager
Subclasses | CDbAuthManager, CPhpAuthManager
Since | 1.0
Version | $Id: CAuthManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAuthManager is the base class for authorization manager classes.

CAuthManager extends CApplicationComponent and implements some methods that are common among authorization manager classes.

CAuthManager together with its concrete child classes implement the Role-Based Access Control (RBAC).

The main idea is that permissions are organized as a hierarchy of authorization items. Items on higer level inherit the permissions represented by items on lower level. And roles are simply top-level authorization items that may be assigned to individual users. A user is said to have a permission to do something if the corresponding authorization item is inherited by one of his roles.

Using authorization manager consists of two aspects. First, the authorization hierarchy and assignments have to be established. CAuthManager and its child classes provides APIs to accomplish this task. Developers may need to develop some GUI so that it is more intuitive to end-users. Second, developers call IAuthManager::checkAccess at appropriate places in the application code to check if the current user has the needed permission for an operation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
authItems | array | Returns the authorization items of the specific type and user. | IAuthManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
defaultRoles | array | list of role names that are assigned to all users implicitly. | CAuthManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
operations | array | Returns operations. | CAuthManager
roles | array | Returns roles. | CAuthManager
tasks | array | Returns tasks. | CAuthManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addItemChild() | Adds an item as a child of another item. | IAuthManager
asa() | Returns the named behavior object. | CComponent
assign() | Assigns an authorization item to a user. | IAuthManager
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkAccess() | Performs access check for the specified user. | IAuthManager
clearAll() | Removes all authorization data. | IAuthManager
clearAuthAssignments() | Removes all authorization assignments. | IAuthManager
createAuthItem() | Creates an authorization item. | IAuthManager
createOperation() | Creates an operation. | CAuthManager
createRole() | Creates a role. | CAuthManager
createTask() | Creates a task. | CAuthManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
executeBizRule() | Executes the specified business rule. | CAuthManager
getAuthAssignment() | Returns the item assignment information. | IAuthManager
getAuthAssignments() | Returns the item assignments for the specified user. | IAuthManager
getAuthItem() | Returns the authorization item with the specified name. | IAuthManager
getAuthItems() | Returns the authorization items of the specific type and user. | IAuthManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getItemChildren() | Returns the children of the specified item. | IAuthManager
getOperations() | Returns operations. | CAuthManager
getRoles() | Returns roles. | CAuthManager
getTasks() | Returns tasks. | CAuthManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasItemChild() | Returns a value indicating whether a child exists within a parent. | IAuthManager
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
isAssigned() | Returns a value indicating whether the item has been assigned to the user. | IAuthManager
raiseEvent() | Raises an event. | CComponent
removeAuthItem() | Removes the specified authorization item. | IAuthManager
removeItemChild() | Removes a child from its parent. | IAuthManager
revoke() | Revokes an authorization assignment from a user. | IAuthManager
save() | Saves authorization data into persistent storage. | IAuthManager
saveAuthAssignment() | Saves the changes to an authorization assignment. | IAuthManager
saveAuthItem() | Saves an authorization item to persistent storage. | IAuthManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
checkItemChildType() | Checks the item types to make sure a child can be added to a parent. | CAuthManager

Property Details

defaultRoles property (available since v1.0.3)
public array $defaultRoles;

list of role names that are assigned to all users implicitly. These roles do not need to be explicitly assigned to any user. When calling checkAccess, these roles will be checked first. For performance reason, you should minimize the number of such roles. A typical usage of such roles is to define an 'authenticated' role and associate it with a biz rule which checks if the current user is authenticated. And then declare 'authenticated' in this property so that it can be applied to every authenticated user.

operations property read-only
public array getOperations(mixed $userId=NULL)

Returns operations. This is a shortcut method to IAuthManager::getAuthItems.

roles property read-only
public array getRoles(mixed $userId=NULL)

Returns roles. This is a shortcut method to IAuthManager::getAuthItems.

tasks property read-only
public array getTasks(mixed $userId=NULL)

Returns tasks. This is a shortcut method to IAuthManager::getAuthItems.

Method Details

checkItemChildType() method
protected void checkItemChildType(integer $parentType, integer $childType)
$parentType | integer | parent item type
$childType | integer | child item type

Checks the item types to make sure a child can be added to a parent.

createOperation() method
public void createOperation(string $name, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name
$description | string | the item description.
$bizRule | string | the business rule associated with this item
$data | mixed | additional data to be passed when evaluating the business rule

Creates an operation. This is a shortcut method to IAuthManager::createAuthItem.

createRole() method
public void createRole(string $name, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name
$description | string | the item description.
$bizRule | string | the business rule associated with this item
$data | mixed | additional data to be passed when evaluating the business rule

Creates a role. This is a shortcut method to IAuthManager::createAuthItem.

createTask() method
public void createTask(string $name, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name
$description | string | the item description.
$bizRule | string | the business rule associated with this item
$data | mixed | additional data to be passed when evaluating the business rule

Creates a task. This is a shortcut method to IAuthManager::createAuthItem.

executeBizRule() method
public boolean executeBizRule(string $bizRule, array $params, mixed $data)
$bizRule | string | the business rule to be executed.
$params | array | parameters passed to IAuthManager::checkAccess.
$data | mixed | additional data associated with the authorization item or assignment.
{return} | boolean | whether the business rule returns true. If the business rule is empty, it will still return true.

Executes the specified business rule.

getOperations() method
public array getOperations(mixed $userId=NULL)
$userId | mixed | the user ID. If not null, only the operations directly assigned to the user will be returned. Otherwise, all operations will be returned.
{return} | array | operations (name=>CAuthItem)

Returns operations. This is a shortcut method to IAuthManager::getAuthItems.

getRoles() method
public array getRoles(mixed $userId=NULL)
$userId | mixed | the user ID. If not null, only the roles directly assigned to the user will be returned. Otherwise, all roles will be returned.
{return} | array | roles (name=>CAuthItem)

Returns roles. This is a shortcut method to IAuthManager::getAuthItems.

getTasks() method
public array getTasks(mixed $userId=NULL)
$userId | mixed | the user ID. If not null, only the tasks directly assigned to the user will be returned. Otherwise, all tasks will be returned.
{return} | array | tasks (name=>CAuthItem)

Returns tasks. This is a shortcut method to IAuthManager::getAuthItems.


CBaseUserIdentity

Package | system.web.auth
Inheritance | abstract class CBaseUserIdentity » CComponent
Implements | IUserIdentity
Subclasses | CUserIdentity
Since | 1.0
Version | $Id: CBaseUserIdentity.php 1896 2010-03-13 14:11:24Z qiang.xue $
CBaseUserIdentity is a base class implementing IUserIdentity.

CBaseUserIdentity implements the scheme for representing identity information that needs to be persisted. It also provides the way to represent the authentication errors.

Derived classes should implement IUserIdentity::authenticate and IUserIdentity::getId that are required by the IUserIdentity interface.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
errorCode | integer | the authentication error code. | CBaseUserIdentity
errorMessage | string | the authentication error message. | CBaseUserIdentity
id | mixed | Returns a value that uniquely represents the identity. | CBaseUserIdentity
isAuthenticated | whether | Returns a value indicating whether the identity is authenticated. | CBaseUserIdentity
name | string | Returns the display name for the identity (e.g. username). | CBaseUserIdentity
persistentStates | array | Returns the identity states that should be persisted. | CBaseUserIdentity

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
authenticate() | Authenticates the user. | IUserIdentity
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearState() | Removes the specified state. | CBaseUserIdentity
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() | Returns a value that uniquely represents the identity. | CBaseUserIdentity
getIsAuthenticated() | Returns a value indicating whether the identity is authenticated. | CBaseUserIdentity
getName() | Returns the display name for the identity (e.g. username). | CBaseUserIdentity
getPersistentStates() | Returns the identity states that should be persisted. | CBaseUserIdentity
getState() | Gets the persisted state by the specified name. | CBaseUserIdentity
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setPersistentStates() | Sets an array of presistent states. | CBaseUserIdentity
setState() | Sets the named state with a given value. | CBaseUserIdentity

Property Details

errorCode property
public integer $errorCode;

the authentication error code. If there is an error, the error code will be non-zero. Defaults to 100, meaning unknown identity. Calling authenticate will change this value.

errorMessage property
public string $errorMessage;

the authentication error message. Defaults to empty.

id property read-only
public mixed getId()

Returns a value that uniquely represents the identity.

isAuthenticated property read-only
public whether getIsAuthenticated()

Returns a value indicating whether the identity is authenticated. This method is required by IUserIdentity.

name property read-only
public string getName()

Returns the display name for the identity (e.g. username).

persistentStates property
public array getPersistentStates()
public void setPersistentStates($states $states)

Returns the identity states that should be persisted. This method is required by IUserIdentity.

Method Details

clearState() method (available since v1.0.8)
public void clearState(string $name)
$name string the name of the state

Removes the specified state.

getId() method
public mixed getId()
{return} mixed a value that uniquely represents the identity (e.g. primary key value). The default implementation simply returns name.

Returns a value that uniquely represents the identity.

getIsAuthenticated() method
public whether getIsAuthenticated()
{return} whether the authentication is successful.

Returns a value indicating whether the identity is authenticated. This method is required by IUserIdentity.

getName() method
public string getName()
{return} string the display name for the identity. The default implementation simply returns empty string.

Returns the display name for the identity (e.g. username).

getPersistentStates() method
public array getPersistentStates()
{return} array the identity states that should be persisted.

Returns the identity states that should be persisted. This method is required by IUserIdentity.

getState() method
public mixed getState(string $name, mixed $defaultValue=NULL)
$name | string | the name of the state
$defaultValue | mixed | the default value to be returned if the named state does not exist
{return} | mixed | the value of the named state

Gets the persisted state by the specified name.

setPersistentStates() method
public void setPersistentStates($states $states)
$states $states array the identity states that should be persisted.

Sets an array of presistent states.

setState() method
public void setState(string $name, mixed $value)
$name | string | the name of the state
$value | mixed | the value of the named state

Sets the named state with a given value.


CDbAuthManager

Package | system.web.auth
Inheritance | class CDbAuthManager » CAuthManager » CApplicationComponent » CComponent
Implements | IAuthManager, IApplicationComponent
Since | 1.0
Version | $Id: CDbAuthManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CDbAuthManager represents an authorization manager that stores authorization information in database.

The database connection is specified by connectionID. And the database schema should be as described in "framework/web/auth/schema.sql". You may change the names of the three tables used to store the authorization data by setting itemTable, itemChildTable and assignmentTable.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
assignmentTable | string | the name of the table storing authorization item assignments. | CDbAuthManager
authItems | array | Returns the authorization items of the specific type and user. | CDbAuthManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
connectionID | string | the ID of the CDbConnection application component. | CDbAuthManager
db | CDbConnection | the database connection. | CDbAuthManager
defaultRoles | array | list of role names that are assigned to all users implicitly. | CAuthManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
itemChildTable | string | the name of the table storing authorization item hierarchy. | CDbAuthManager
itemTable | string | the name of the table storing authorization items. | CDbAuthManager
operations | array | Returns operations. | CAuthManager
roles | array | Returns roles. | CAuthManager
tasks | array | Returns tasks. | CAuthManager

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
dbConnection | CDbConnection | the DB connection instance | CDbAuthManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__destruct() | Destructor. | CDbAuthManager
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addItemChild() | Adds an item as a child of another item. | CDbAuthManager
asa() | Returns the named behavior object. | CComponent
assign() | Assigns an authorization item to a user. | CDbAuthManager
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkAccess() | Performs access check for the specified user. | CDbAuthManager
clearAll() | Removes all authorization data. | CDbAuthManager
clearAuthAssignments() | Removes all authorization assignments. | CDbAuthManager
createAuthItem() | Creates an authorization item. | CDbAuthManager
createOperation() | Creates an operation. | CAuthManager
createRole() | Creates a role. | CAuthManager
createTask() | Creates a task. | CAuthManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
executeBizRule() | Executes the specified business rule. | CAuthManager
getAuthAssignment() | Returns the item assignment information. | CDbAuthManager
getAuthAssignments() | Returns the item assignments for the specified user. | CDbAuthManager
getAuthItem() | Returns the authorization item with the specified name. | CDbAuthManager
getAuthItems() | Returns the authorization items of the specific type and user. | CDbAuthManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getItemChildren() | Returns the children of the specified item. | CDbAuthManager
getOperations() | Returns operations. | CAuthManager
getRoles() | Returns roles. | CAuthManager
getTasks() | Returns tasks. | CAuthManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasItemChild() | Returns a value indicating whether a child exists within a parent. | CDbAuthManager
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CDbAuthManager
isAssigned() | Returns a value indicating whether the item has been assigned to the user. | CDbAuthManager
raiseEvent() | Raises an event. | CComponent
removeAuthItem() | Removes the specified authorization item. | CDbAuthManager
removeItemChild() | Removes a child from its parent. | CDbAuthManager
revoke() | Revokes an authorization assignment from a user. | CDbAuthManager
save() | Saves the authorization data to persistent storage. | CDbAuthManager
saveAuthAssignment() | Saves the changes to an authorization assignment. | CDbAuthManager
saveAuthItem() | Saves an authorization item to persistent storage. | CDbAuthManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
checkDefaultRoles() | Checks the access based on the default roles as declared in defaultRoles. | CDbAuthManager
checkItemChildType() | Checks the item types to make sure a child can be added to a parent. | CAuthManager
detectLoop() | Checks whether there is a loop in the authorization item hierarchy. | CDbAuthManager
getDbConnection() |  | CDbAuthManager
usingSqlite() |  | CDbAuthManager

Property Details

assignmentTable property
public string $assignmentTable;

the name of the table storing authorization item assignments. Defaults to 'AuthAssignment'.

authItems property read-only
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)

Returns the authorization items of the specific type and user.

connectionID property
public string $connectionID;

the ID of the CDbConnection application component. Defaults to 'db'. The database must have the tables as declared in "framework/web/auth/schema.sql".

db property
public CDbConnection $db;

the database connection. By default, this is initialized automatically as the application component whose ID is indicated as connectionID.

dbConnection property read-only
protected CDbConnection getDbConnection()

the DB connection instance

itemChildTable property
public string $itemChildTable;

the name of the table storing authorization item hierarchy. Defaults to 'AuthItemChild'.

itemTable property
public string $itemTable;

the name of the table storing authorization items. Defaults to 'AuthItem'.

Method Details

__destruct() method
public void __destruct()

Destructor. Disconnect the db connection.

addItemChild() method
public void addItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name

Adds an item as a child of another item.

assign() method
public CAuthAssignment assign(string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
$bizRule | string | the business rule to be executed when checkAccess is called for this particular authorization item.
$data | mixed | additional data associated with this assignment
{return} | CAuthAssignment | the authorization assignment information.

Assigns an authorization item to a user.

checkAccess() method
public boolean checkAccess(string $itemName, mixed $userId, array $params=array ( ))
$itemName | string | the name of the operation that need access check
$userId | mixed | the user ID. This should can be either an integer and a string representing the unique identifier of a user. See IWebUser::getId.
$params | array | name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by the user.

Performs access check for the specified user.

checkDefaultRoles() method (available since v1.0.3)
protected boolean checkDefaultRoles(string $itemName, array $params)
$itemName | string | the name of the operation that need access check
$params | array | name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by the user according to the default roles.

Checks the access based on the default roles as declared in defaultRoles.

clearAll() method
public void clearAll()

Removes all authorization data.

clearAuthAssignments() method
public void clearAuthAssignments()

Removes all authorization assignments.

createAuthItem() method
public CAuthItem createAuthItem(string $name, integer $type, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name. This must be a unique identifier.
$type | integer | the item type (0: operation, 1: task, 2: role).
$description | string | description of the item
$bizRule | string | business rule associated with the item. This is a piece of PHP code that will be executed when checkAccess is called for the item.
$data | mixed | additional data associated with the item.
{return} | CAuthItem | the authorization item

Creates an authorization item. An authorization item represents an action permission (e.g. creating a post). It has three types: operation, task and role. Authorization items form a hierarchy. Higher level items inheirt permissions representing by lower level items.

detectLoop() method
protected boolean detectLoop(string $itemName, string $childName)
$itemName | string | parent item name
$childName | string | the name of the child item that is to be added to the hierarchy
{return} | boolean | whether a loop exists

Checks whether there is a loop in the authorization item hierarchy.

getAuthAssignment() method
public CAuthAssignment getAuthAssignment(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | CAuthAssignment | the item assignment information. Null is returned if the item is not assigned to the user.

Returns the item assignment information.

getAuthAssignments() method
public array getAuthAssignments(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | array | the item assignment information for the user. An empty array will be returned if there is no item assigned to the user.

Returns the item assignments for the specified user.

getAuthItem() method
public CAuthItem getAuthItem(string $name)
$name | string | the name of the item
{return} | CAuthItem | the authorization item. Null if the item cannot be found.

Returns the authorization item with the specified name.

getAuthItems() method
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)
$type | integer | the item type (0: operation, 1: task, 2: role). Defaults to null, meaning returning all items regardless of their type.
$userId | mixed | the user ID. Defaults to null, meaning returning all items even if they are not assigned to a user.
{return} | array | the authorization items of the specific type.

Returns the authorization items of the specific type and user.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance

getItemChildren() method
public array getItemChildren(mixed $names)
$names | mixed | the parent item name. This can be either a string or an array. The latter represents a list of item names (available since version 1.0.5).
{return} | array | all child items of the parent

Returns the children of the specified item.

hasItemChild() method
public boolean hasItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the child exists

Returns a value indicating whether a child exists within a parent.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by establishing the database connection.

isAssigned() method
public boolean isAssigned(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether the item has been assigned to the user.

Returns a value indicating whether the item has been assigned to the user.

removeAuthItem() method
public boolean removeAuthItem(string $name)
$name | string | the name of the item to be removed
{return} | boolean | whether the item exists in the storage and has been removed

Removes the specified authorization item.

removeItemChild() method
public boolean removeItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the removal is successful

Removes a child from its parent. Note, the child item is not deleted. Only the parent-child relationship is removed.

revoke() method
public boolean revoke(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether removal is successful

Revokes an authorization assignment from a user.

save() method
public void save()

Saves the authorization data to persistent storage.

saveAuthAssignment() method
public void saveAuthAssignment(CAuthAssignment $assignment)
$assignment CAuthAssignment the assignment that has been changed.

Saves the changes to an authorization assignment.

saveAuthItem() method
public void saveAuthItem(CAuthItem $item, string $oldName=NULL)
$item | CAuthItem | the item to be saved.
$oldName | string | the old item name. If null, it means the item name is not changed.

Saves an authorization item to persistent storage.

usingSqlite() method
protected boolean usingSqlite()
{return} boolean whether the database is a SQLite database


CPhpAuthManager

Package | system.web.auth
Inheritance | class CPhpAuthManager » CAuthManager » CApplicationComponent » CComponent
Implements | IAuthManager, IApplicationComponent
Since | 1.0
Version | $Id: CPhpAuthManager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPhpAuthManager represents an authorization manager that stores authorization information in terms of a PHP script file.

The authorization data will be saved to and loaded from a file specified by authFile, which defaults to 'protected/data/auth.php'.

CPhpAuthManager is mainly suitable for authorization data that is not too big (for example, the authorization data for a personal blog system). Use CDbAuthManager for more complex authorization data.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
authFile | string | the path of the PHP script that contains the authorization data. | CPhpAuthManager
authItems | array | Returns the authorization items of the specific type and user. | CPhpAuthManager
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
defaultRoles | array | list of role names that are assigned to all users implicitly. | CAuthManager
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
operations | array | Returns operations. | CAuthManager
roles | array | Returns roles. | CAuthManager
tasks | array | Returns tasks. | CAuthManager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
addItemChild() | Adds an item as a child of another item. | CPhpAuthManager
asa() | Returns the named behavior object. | CComponent
assign() | Assigns an authorization item to a user. | CPhpAuthManager
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkAccess() | Performs access check for the specified user. | CPhpAuthManager
clearAll() | Removes all authorization data. | CPhpAuthManager
clearAuthAssignments() | Removes all authorization assignments. | CPhpAuthManager
createAuthItem() | Creates an authorization item. | CPhpAuthManager
createOperation() | Creates an operation. | CAuthManager
createRole() | Creates a role. | CAuthManager
createTask() | Creates a task. | CAuthManager
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
executeBizRule() | Executes the specified business rule. | CAuthManager
getAuthAssignment() | Returns the item assignment information. | CPhpAuthManager
getAuthAssignments() | Returns the item assignments for the specified user. | CPhpAuthManager
getAuthItem() | Returns the authorization item with the specified name. | CPhpAuthManager
getAuthItems() | Returns the authorization items of the specific type and user. | CPhpAuthManager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
getItemChildren() | Returns the children of the specified item. | CPhpAuthManager
getOperations() | Returns operations. | CAuthManager
getRoles() | Returns roles. | CAuthManager
getTasks() | Returns tasks. | CAuthManager
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasItemChild() | Returns a value indicating whether a child exists within a parent. | CPhpAuthManager
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CPhpAuthManager
isAssigned() | Returns a value indicating whether the item has been assigned to the user. | CPhpAuthManager
load() | Loads authorization data. | CPhpAuthManager
raiseEvent() | Raises an event. | CComponent
removeAuthItem() | Removes the specified authorization item. | CPhpAuthManager
removeItemChild() | Removes a child from its parent. | CPhpAuthManager
revoke() | Revokes an authorization assignment from a user. | CPhpAuthManager
save() | Saves authorization data into persistent storage. | CPhpAuthManager
saveAuthAssignment() | Saves the changes to an authorization assignment. | CPhpAuthManager
saveAuthItem() | Saves an authorization item to persistent storage. | CPhpAuthManager

Protected Methods

Hide inherited methods

Method | Description | Defined By
checkDefaultRoles() | Checks the access based on the default roles as declared in defaultRoles. | CPhpAuthManager
checkItemChildType() | Checks the item types to make sure a child can be added to a parent. | CAuthManager
detectLoop() | Checks whether there is a loop in the authorization item hierarchy. | CPhpAuthManager
loadFromFile() | Loads the authorization data from a PHP script file. | CPhpAuthManager
saveToFile() | Saves the authorization data to a PHP script file. | CPhpAuthManager

Property Details

authFile property
public string $authFile;

the path of the PHP script that contains the authorization data. If not set, it will be using 'protected/data/auth.php' as the data file. Make sure this file is writable by the Web server process if the authorization needs to be changed.

See Also

  • loadFromFile
  • saveToFile
authItems property read-only
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)

Returns the authorization items of the specific type and user.

Method Details

addItemChild() method
public void addItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name

Adds an item as a child of another item.

assign() method
public CAuthAssignment assign(string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
$bizRule | string | the business rule to be executed when checkAccess is called for this particular authorization item.
$data | mixed | additional data associated with this assignment
{return} | CAuthAssignment | the authorization assignment information.

Assigns an authorization item to a user.

checkAccess() method
public boolean checkAccess(string $itemName, mixed $userId, array $params=array ( ))
$itemName | string | the name of the operation that need access check
$userId | mixed | the user ID. This should can be either an integer and a string representing the unique identifier of a user. See IWebUser::getId.
$params | array | name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by the user.

Performs access check for the specified user.

checkDefaultRoles() method (available since v1.0.3)
protected boolean checkDefaultRoles(string $itemName, array $params)
$itemName | string | the name of the operation that need access check
$params | array | name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} | boolean | whether the operations can be performed by the user according to the default roles.

Checks the access based on the default roles as declared in defaultRoles.

clearAll() method
public void clearAll()

Removes all authorization data.

clearAuthAssignments() method
public void clearAuthAssignments()

Removes all authorization assignments.

createAuthItem() method
public CAuthItem createAuthItem(string $name, integer $type, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name | string | the item name. This must be a unique identifier.
$type | integer | the item type (0: operation, 1: task, 2: role).
$description | string | description of the item
$bizRule | string | business rule associated with the item. This is a piece of PHP code that will be executed when checkAccess is called for the item.
$data | mixed | additional data associated with the item.
{return} | CAuthItem | the authorization item

Creates an authorization item. An authorization item represents an action permission (e.g. creating a post). It has three types: operation, task and role. Authorization items form a hierarchy. Higher level items inheirt permissions representing by lower level items.

detectLoop() method
protected boolean detectLoop(string $itemName, string $childName)
$itemName | string | parent item name
$childName | string | the name of the child item that is to be added to the hierarchy
{return} | boolean | whether a loop exists

Checks whether there is a loop in the authorization item hierarchy.

getAuthAssignment() method
public CAuthAssignment getAuthAssignment(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | CAuthAssignment | the item assignment information. Null is returned if the item is not assigned to the user.

Returns the item assignment information.

getAuthAssignments() method
public array getAuthAssignments(mixed $userId)
$userId | mixed | the user ID (see IWebUser::getId)
{return} | array | the item assignment information for the user. An empty array will be returned if there is no item assigned to the user.

Returns the item assignments for the specified user.

getAuthItem() method
public CAuthItem getAuthItem(string $name)
$name | string | the name of the item
{return} | CAuthItem | the authorization item. Null if the item cannot be found.

Returns the authorization item with the specified name.

getAuthItems() method
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)
$type | integer | the item type (0: operation, 1: task, 2: role). Defaults to null, meaning returning all items regardless of their type.
$userId | mixed | the user ID. Defaults to null, meaning returning all items even if they are not assigned to a user.
{return} | array | the authorization items of the specific type.

Returns the authorization items of the specific type and user.

getItemChildren() method
public array getItemChildren(mixed $names)
$names | mixed | the parent item name. This can be either a string or an array. The latter represents a list of item names (available since version 1.0.5).
{return} | array | all child items of the parent

Returns the children of the specified item.

hasItemChild() method
public boolean hasItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the child exists

Returns a value indicating whether a child exists within a parent.

init() method
public void init()

Initializes the application component. This method overrides parent implementation by loading the authorization data from PHP script.

isAssigned() method
public boolean isAssigned(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether the item has been assigned to the user.

Returns a value indicating whether the item has been assigned to the user.

load() method
public void load()

Loads authorization data.

loadFromFile() method
protected array loadFromFile(string $file)
$file | string | the file path.
{return} | array | the authorization data

Loads the authorization data from a PHP script file.

See Also

  • saveToFile
removeAuthItem() method
public boolean removeAuthItem(string $name)
$name | string | the name of the item to be removed
{return} | boolean | whether the item exists in the storage and has been removed

Removes the specified authorization item.

removeItemChild() method
public boolean removeItemChild(string $itemName, string $childName)
$itemName | string | the parent item name
$childName | string | the child item name
{return} | boolean | whether the removal is successful

Removes a child from its parent. Note, the child item is not deleted. Only the parent-child relationship is removed.

revoke() method
public boolean revoke(string $itemName, mixed $userId)
$itemName | string | the item name
$userId | mixed | the user ID (see IWebUser::getId)
{return} | boolean | whether removal is successful

Revokes an authorization assignment from a user.

save() method
public void save()

Saves authorization data into persistent storage. If any change is made to the authorization data, please make sure you call this method to save the changed data into persistent storage.

saveAuthAssignment() method
public void saveAuthAssignment(CAuthAssignment $assignment)
$assignment CAuthAssignment the assignment that has been changed.

Saves the changes to an authorization assignment.

saveAuthItem() method
public void saveAuthItem(CAuthItem $item, string $oldName=NULL)
$item | CAuthItem | the item to be saved.
$oldName | string | the old item name. If null, it means the item name is not changed.

Saves an authorization item to persistent storage.

saveToFile() method
protected void saveToFile(array $data, string $file)
$data | array | the authorization data
$file | string | the file path.

Saves the authorization data to a PHP script file.

See Also

  • loadFromFile


CUserIdentity

Package | system.web.auth
Inheritance | class CUserIdentity » CBaseUserIdentity » CComponent
Implements | IUserIdentity
Since | 1.0
Version | $Id: CUserIdentity.php 1678 2010-01-07 21:02:00Z qiang.xue $
CUserIdentity is a base class for representing identities that are authenticated based on a username and a password.

Derived classes should implement authenticate with the actual authentication scheme (e.g. checking username and password against a DB table).

By default, CUserIdentity assumes the username is a unique identifier and thus use it as the ID of the identity.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
errorCode | integer | the authentication error code. | CBaseUserIdentity
errorMessage | string | the authentication error message. | CBaseUserIdentity
id | string | Returns the unique identifier for the identity. | CUserIdentity
isAuthenticated | whether | Returns a value indicating whether the identity is authenticated. | CBaseUserIdentity
name | string | Returns the display name for the identity. | CUserIdentity
password | string | password | CUserIdentity
persistentStates | array | Returns the identity states that should be persisted. | CBaseUserIdentity
username | string | username | CUserIdentity

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CUserIdentity
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
authenticate() | Authenticates a user based on username and password. | CUserIdentity
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clearState() | Removes the specified state. | CBaseUserIdentity
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() | Returns the unique identifier for the identity. | CUserIdentity
getIsAuthenticated() | Returns a value indicating whether the identity is authenticated. | CBaseUserIdentity
getName() | Returns the display name for the identity. | CUserIdentity
getPersistentStates() | Returns the identity states that should be persisted. | CBaseUserIdentity
getState() | Gets the persisted state by the specified name. | CBaseUserIdentity
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setPersistentStates() | Sets an array of presistent states. | CBaseUserIdentity
setState() | Sets the named state with a given value. | CBaseUserIdentity

Property Details

id property read-only
public string getId()

Returns the unique identifier for the identity. The default implementation simply returns username. This method is required by IUserIdentity.

name property read-only
public string getName()

Returns the display name for the identity. The default implementation simply returns username. This method is required by IUserIdentity.

password property
public string $password;

password

username property
public string $username;

username

Method Details

__construct() method
public void __construct(string $username, string $password)
$username | string | username
$password | string | password

Constructor.

authenticate() method
public boolean authenticate()
{return} boolean whether authentication succeeds.

Authenticates a user based on username and password. Derived classes should override this method, or an exception will be thrown. This method is required by IUserIdentity.

getId() method
public string getId()
{return} string the unique identifier for the identity.

Returns the unique identifier for the identity. The default implementation simply returns username. This method is required by IUserIdentity.

getName() method
public string getName()
{return} string the display name for the identity.

Returns the display name for the identity. The default implementation simply returns username. This method is required by IUserIdentity.


CWebUser

Package | system.web.auth
Inheritance | class CWebUser » CApplicationComponent » CComponent
Implements | IApplicationComponent, IWebUser
Since | 1.0
Version | $Id: CWebUser.php 1832 2010-02-20 03:22:45Z qiang.xue $
CWebUser represents the persistent state for a Web application user.

CWebUser is used as an application component whose ID is 'user'. Therefore, at any place one can access the user state via Yii::app()->user.

CWebUser should be used together with an identity which implements the actual authentication algorithm.

A typical authentication process using CWebUser is as follows:
  1. The user provides information needed for authentication.
  2. An identity instance is created with the user-provided information.
  3. Call IUserIdentity::authenticate to check if the identity is valid.
  4. If valid, call CWebUser::login to login the user, and Redirect the user browser to returnUrl.
  5. If not valid, retrieve the error code or message from the identity instance and display it.

The property id and name are both unique identifiers for the user. The former is mainly used internally (e.g. primary key), while the latter is for display purpose (e.g. username). is a unique identifier for a user that is persistent during the whole user session. It can be a username, or something else, depending on the implementation of the identity class.

Both id and name are persistent during the user session. Besides, an identity may have additional persistent data which can be accessed by calling getState. Note, when cookie-based authentication is enabled, all these persistent data will be stored in cookie. Therefore, do not store password or other sensitive data in the persistent storage. Instead, you should store them directly in session on the server side if needed.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
allowAutoLogin | boolean | whether to enable cookie-based login. | CWebUser
autoRenewCookie | boolean | whether to automatically renew the identity cookie each time a page is requested. | CWebUser
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
guestName | string | the name for a guest user. | CWebUser
id | mixed | the unique identifier for the user. | CWebUser
identityCookie | array | the property values (in name-value pairs) used to initialize the identity cookie. | CWebUser
isGuest | boolean | whether the current application user is a guest. | CWebUser
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
loginUrl | string|array | the URL for login. | CWebUser
name | string | Returns the unique identifier for the user (e.g. username). | CWebUser
returnUrl | string | Returns the URL that the user should be redirected to after successful login. | CWebUser
stateKeyPrefix | string | a prefix for the name of the session variables storing user session data. | CWebUser

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | PHP magic method. | CWebUser
__isset() | PHP magic method. | CWebUser
__set() | PHP magic method. | CWebUser
__unset() | PHP magic method. | CWebUser
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkAccess() | Performs access check for this user. | CWebUser
clearStates() | Clears all user identity information from persistent storage. | CWebUser
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getFlash() | Returns a flash message. | CWebUser
getId() |  | CWebUser
getIsGuest() |  | CWebUser
getIsInitialized() |  | CApplicationComponent
getName() | Returns the unique identifier for the user (e.g. username). | CWebUser
getReturnUrl() | Returns the URL that the user should be redirected to after successful login. | CWebUser
getState() | Returns the value of a variable that is stored in user session. | CWebUser
getStateKeyPrefix() |  | CWebUser
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasFlash() |  | CWebUser
hasProperty() | Determines whether a property is defined. | CComponent
hasState() | Returns a value indicating whether there is a state of the specified name. | CWebUser
init() | Initializes the application component. | CWebUser
login() | Logs in a user. | CWebUser
loginRequired() | Redirects the user browser to the login page. | CWebUser
logout() | Logs out the current user. | CWebUser
raiseEvent() | Raises an event. | CComponent
setFlash() | Stores a flash message. | CWebUser
setId() |  | CWebUser
setName() | Sets the unique identifier for the user (e.g. username). | CWebUser
setReturnUrl() |  | CWebUser
setState() | Stores a variable in user session. | CWebUser
setStateKeyPrefix() |  | CWebUser

Protected Methods

Hide inherited methods

Method | Description | Defined By
changeIdentity() | Changes the current user with the specified identity information. | CWebUser
createIdentityCookie() | Creates a cookie to store identity information. | CWebUser
loadIdentityStates() | Loads identity states from an array and saves them to persistent storage. | CWebUser
restoreFromCookie() | Populates the current user object with the information obtained from cookie. | CWebUser
saveIdentityStates() | Retrieves identity states from persistent storage and saves them as an array. | CWebUser
saveToCookie() | Saves necessary user data into a cookie. | CWebUser
updateFlash() | Updates the internal counters for flash messages. | CWebUser

Property Details

allowAutoLogin property
public boolean $allowAutoLogin;

whether to enable cookie-based login. Defaults to false.

autoRenewCookie property (available since v1.1.0)
public boolean $autoRenewCookie;

whether to automatically renew the identity cookie each time a page is requested. Defaults to false. This property is effective only when allowAutoLogin is true. When this is false, the identity cookie will expire after the specified duration since the user is initially logged in. When this is true, the identity cookie will expire after the specified duration since the user visits the site the last time.

See Also

  • allowAutoLogin
guestName property
public string $guestName;

the name for a guest user. Defaults to 'Guest'. This is used by getName when the current user is a guest (not authenticated).

id property
public mixed getId()
public void setId(mixed $value)

the unique identifier for the user. If null, it means the user is a guest.

identityCookie property (available since v1.0.5)
public array $identityCookie;

the property values (in name-value pairs) used to initialize the identity cookie. Any property of CHttpCookie may be initialized. This property is effective only when allowAutoLogin is true.

isGuest property read-only
public boolean getIsGuest()

whether the current application user is a guest.

loginUrl property
public string|array $loginUrl;

the URL for login. If using array, the first element should be the route to the login action, and the rest name-value pairs are GET parameters to construct the login URL (e.g. array('/site/login')). If this property is null, a 403 HTTP exception will be raised instead.

See Also

  • CController::createUrl
name property
public string getName()
public void setName(string $value)

Returns the unique identifier for the user (e.g. username). This is the unique identifier that is mainly used for display purpose.

returnUrl property
public string getReturnUrl()
public void setReturnUrl(string $value)

Returns the URL that the user should be redirected to after successful login. This property is usually used by the login action. If the login is successful, the action should read this property and use it to redirect the user browser.

See Also

  • loginRequired
stateKeyPrefix property
public string getStateKeyPrefix()
public void setStateKeyPrefix(string $value)

a prefix for the name of the session variables storing user session data.

Method Details

__get() method (available since v1.0.3)
public mixed __get(string $name)
$name | string | property name
{return} | mixed | property value

PHP magic method. This method is overriden so that persistent states can be accessed like properties.

__isset() method (available since v1.0.3)
public void __isset(string $name)
$name string property name

PHP magic method. This method is overriden so that persistent states can also be checked for null value.

__set() method (available since v1.0.3)
public void __set(string $name, mixed $value)
$name | string | property name
$value | mixed | property value

PHP magic method. This method is overriden so that persistent states can be set like properties.

__unset() method (available since v1.0.3)
public void __unset(string $name)
$name string property name

PHP magic method. This method is overriden so that persistent states can also be unset.

changeIdentity() method
protected void changeIdentity(mixed $id, string $name, array $states)
$id | mixed | a unique identifier for the user
$name | string | the display name for the user
$states | array | identity states

Changes the current user with the specified identity information. This method is called by login and restoreFromCookie when the current user needs to be populated with the corresponding identity information. Derived classes may override this method by retrieving additional user-related information. Make sure the parent implementation is called first.

checkAccess() method
public boolean checkAccess(string $operation, array $params=array ( ), boolean $allowCaching=true)
$operation | string | the name of the operation that need access check.
$params | array | name-value pairs that would be passed to business rules associated with the tasks and roles assigned to the user.
$allowCaching | boolean | whether to allow caching the result of access checki. This parameter has been available since version 1.0.5. When this parameter is true (default), if the access check of an operation was performed before, its result will be directly returned when calling this method to check the same operation. If this parameter is false, this method will always call CAuthManager::checkAccess to obtain the up-to-date access result. Note that this caching is effective only within the same request.
{return} | boolean | whether the operations can be performed by this user.

Performs access check for this user.

clearStates() method
public void clearStates()

Clears all user identity information from persistent storage. This will remove the data stored via setState.

createIdentityCookie() method (available since v1.0.5)
protected CHttpCookie createIdentityCookie(string $name)
$name | string | the cookie name
{return} | CHttpCookie | the cookie used to store identity information

Creates a cookie to store identity information.

getFlash() method
public mixed getFlash(string $key, mixed $defaultValue=NULL, boolean $delete=true)
$key | string | key identifying the flash message
$defaultValue | mixed | value to be returned if the flash message is not available.
$delete | boolean | whether to delete this flash message after accessing it. Defaults to true. This parameter has been available since version 1.0.2.
{return} | mixed | the message message

Returns a flash message. A flash message is available only in the current and the next requests.

getId() method
public mixed getId()
{return} mixed the unique identifier for the user. If null, it means the user is a guest.

getIsGuest() method
public boolean getIsGuest()
{return} boolean whether the current application user is a guest.

getName() method
public string getName()
{return} string the user name. If the user is not logged in, this will be guestName.

Returns the unique identifier for the user (e.g. username). This is the unique identifier that is mainly used for display purpose.

getReturnUrl() method
public string getReturnUrl()
{return} string the URL that the user should be redirected to after login. Defaults to the application entry URL.

Returns the URL that the user should be redirected to after successful login. This property is usually used by the login action. If the login is successful, the action should read this property and use it to redirect the user browser.

See Also

  • loginRequired
getState() method
public mixed getState(string $key, mixed $defaultValue=NULL)
$key | string | variable name
$defaultValue | mixed | default value
{return} | mixed | the value of the variable. If it doesn't exist in the session, the provided default value will be returned

Returns the value of a variable that is stored in user session.

This function is designed to be used by CWebUser descendant classes who want to store additional user information in user session. A variable, if stored in user session using setState can be retrieved back using this function.

See Also

  • setState
getStateKeyPrefix() method
public string getStateKeyPrefix()
{return} string a prefix for the name of the session variables storing user session data.

hasFlash() method
public boolean hasFlash(string $key)
$key | string | key identifying the flash message
{return} | boolean | whether the specified flash message exists

hasState() method (available since v1.0.3)
public boolean hasState(string $key)
$key | string | state name
{return} | boolean | whether there is a state of the specified name.

Returns a value indicating whether there is a state of the specified name.

init() method
public void init()

Initializes the application component. This method overrides the parent implementation by starting session, performing cookie-based authentication if enabled, and updating the flash variables.

loadIdentityStates() method
protected void loadIdentityStates(array $states)
$states array the identity states

Loads identity states from an array and saves them to persistent storage.

login() method
public void login(IUserIdentity $identity, integer $duration=0)
$identity | IUserIdentity | the user identity (which should already be authenticated)
$duration | integer | number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser. If greater than 0, cookie-based login will be used. In this case, allowAutoLogin must be set true, otherwise an exception will be thrown.

Logs in a user.

The user identity information will be saved in storage that is persistent during the user session. By default, the storage is simply the session storage. If the duration parameter is greater than 0, a cookie will be sent to prepare for cookie-based login in future.

Note, you have to set allowAutoLogin to true if you want to allow user to be authenticated based on the cookie information.

loginRequired() method
public void loginRequired()

Redirects the user browser to the login page. Before the redirection, the current URL will be kept in returnUrl so that the user browser may be redirected back to the current page after successful login. Make sure you set loginUrl so that the user browser can be redirected to the specified login URL after calling this method. After calling this method, the current request processing will be terminated.

logout() method
public void logout(boolean $destroySession=true)
$destroySession boolean whether to destroy the whole session. Defaults to true. If false, then clearStates will be called, which removes only the data stored via setState. This parameter has been available since version 1.0.7. Before 1.0.7, the behavior is to destroy the whole session.

Logs out the current user. This will remove authentication-related session data. If the parameter is true, the whole session will be destroyed as well.

restoreFromCookie() method
protected void restoreFromCookie()

Populates the current user object with the information obtained from cookie. This method is used when automatic login (allowAutoLogin) is enabled. The user identity information is recovered from cookie. Sufficient security measures are used to prevent cookie data from being tampered.

See Also

  • saveToCookie
saveIdentityStates() method
protected array saveIdentityStates()
{return} array the identity states

Retrieves identity states from persistent storage and saves them as an array.

saveToCookie() method
protected void saveToCookie(integer $duration)
$duration integer number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser.

Saves necessary user data into a cookie. This method is used when automatic login (allowAutoLogin) is enabled. This method saves user ID, username, other identity states and a validation key to cookie. These information are used to do authentication next time when user visits the application.

See Also

  • restoreFromCookie
setFlash() method
public void setFlash(string $key, mixed $value, mixed $defaultValue=NULL)
$key | string | key identifying the flash message
$value | mixed | flash message
$defaultValue | mixed | if this value is the same as the flash message, the flash message will be removed. (Therefore, you can use setFlash('key',null) to remove a flash message.)

Stores a flash message. A flash message is available only in the current and the next requests.

setId() method
public void setId(mixed $value)
$value mixed the unique identifier for the user. If null, it means the user is a guest.

setName() method
public void setName(string $value)
$value string the user name.

Sets the unique identifier for the user (e.g. username).

See Also

  • getName
setReturnUrl() method
public void setReturnUrl(string $value)
$value string the URL that the user should be redirected to after login.

setState() method
public void setState(string $key, mixed $value, mixed $defaultValue=NULL)
$key | string | variable name
$value | mixed | variable value
$defaultValue | mixed | default value. If $value===$defaultValue, the variable will be removed from the session

Stores a variable in user session.

This function is designed to be used by CWebUser descendant classes who want to store additional user information in user session. By storing a variable using this function, the variable may be retrieved back later using getState. The variable will be persistent across page requests during a user session.

See Also

  • getState
setStateKeyPrefix() method (available since v1.0.9)
public void setStateKeyPrefix(string $value)
$value string a prefix for the name of the session variables storing user session data.

updateFlash() method
protected void updateFlash()

Updates the internal counters for flash messages. This method is internally used by CWebApplication to maintain the availability of flash messages.


CFilter

All Packages | Methods
Package | system.web.filters
Inheritance | class CFilter » CComponent
Implements | IFilter
Subclasses | CAccessControlFilter, CInlineFilter
Since | 1.0
Version | $Id: CFilter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFilter is the base class for all filters.

A filter can be applied before and after an action is executed. It can modify the context that the action is to run or decorate the result that the action generates.

Override preFilter() to specify the filtering logic that should be applied before the action, and postFilter() for filtering logic after the action.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
postFilter() | Performs the post-action filtering. | CFilter
preFilter() | Performs the pre-action filtering. | CFilter

Method Details

filter() method
public void filter(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

Performs the filtering. The default implementation is to invoke preFilter and postFilter which are meant to be overridden child classes. If a child class needs to override this method, make sure it calls $filterChain->run() if the action should be executed.

postFilter() method
protected void postFilter(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

Performs the post-action filtering.

preFilter() method
protected boolean preFilter(CFilterChain $filterChain)
$filterChain | CFilterChain | the filter chain that the filter is on.
{return} | boolean | whether the filtering process should continue and the action should be executed.

Performs the pre-action filtering.


CFilterChain

Package | system.web.filters
Inheritance | class CFilterChain » CList » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.0
Version | $Id: CFilterChain.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFilterChain represents a list of filters being applied to an action.

CFilterChain executes the filter list by run().

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
action | CAction | the action being filtered by this chain. | CFilterChain
controller | CController | the controller who executes the action. | CFilterChain
count | integer | the number of items in the list | CList
filterIndex | integer | the index of the filter that is to be executed when calling run(). | CFilterChain
iterator | Iterator | Returns an iterator for traversing the items in the list. | CList
readOnly | boolean | whether this list is read-only or not. | CList

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterChain
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Appends an item at the end of the list. | CList
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the list. | CList
contains() |  | CList
copyFrom() | Copies iterable data into the list. | CList
count() | Returns the number of items in the list. | CList
create() | CFilterChain factory method. | CFilterChain
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CList
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CList
getReadOnly() |  | CList
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
indexOf() |  | CList
insertAt() | Inserts an item at the specified position. | CFilterChain
itemAt() | Returns the item at the specified offset. | CList
mergeWith() | Merges iterable data into the map. | CList
offsetExists() | Returns whether there is an item at the specified offset. | CList
offsetGet() | Returns the item at the specified offset. | CList
offsetSet() | Sets the item at the specified offset. | CList
offsetUnset() | Unsets the item at the specified offset. | CList
raiseEvent() | Raises an event. | CComponent
remove() | Removes an item from the list. | CList
removeAt() | Removes an item at the specified position. | CList
run() | Executes the filter indexed at filterIndex. | CFilterChain
toArray() |  | CList

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CList

Property Details

action property
public CAction $action;

the action being filtered by this chain.

controller property
public CController $controller;

the controller who executes the action.

filterIndex property
public integer $filterIndex;

the index of the filter that is to be executed when calling run().

Method Details

__construct() method
public void __construct(CController $controller, CAction $action)
$controller | CController | the controller who executes the action.
$action | CAction | the action being filtered by this chain.

Constructor.

create() method
public static void create(CController $controller, CAction $action, array $filters)
$controller | CController | the controller who executes the action.
$action | CAction | the action being filtered by this chain.
$filters | array | list of filters to be applied to the action.

CFilterChain factory method. This method creates a CFilterChain instance.

insertAt() method
public void insertAt(integer $index, mixed $item)
$index | integer | the specified position.
$item | mixed | new item

Inserts an item at the specified position. This method overrides the parent implementation by adding additional check for the item to be added. In particular, only objects implementing IFilter can be added to the list.

run() method
public void run()

Executes the filter indexed at filterIndex. After this method is called, filterIndex will be automatically incremented by one. This method is usually invoked in filters so that the filtering process can continue and the action can be executed.


CInlineFilter

Package | system.web.filters
Inheritance | class CInlineFilter » CFilter » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CInlineFilter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CInlineFilter represents a filter defined as a controller method.

CInlineFilter executes the 'filterXYZ($action)' method defined in the controller, where the name 'XYZ' can be retrieved from the name property.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
name | string | name of the filter. | CInlineFilter

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
create() | Creates an inline filter instance. | CInlineFilter
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CInlineFilter
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Protected Methods

Hide inherited methods

Method | Description | Defined By
postFilter() | Performs the post-action filtering. | CFilter
preFilter() | Performs the pre-action filtering. | CFilter

Property Details

name property
public string $name;

name of the filter. It stands for 'XYZ' in the filter method name 'filterXYZ'.

Method Details

create() method
public static CInlineFilter create(CController $controller, string $filterName)
$controller | CController | the controller who hosts the filter methods
$filterName | string | the filter name
{return} | CInlineFilter | the created instance

Creates an inline filter instance. The creation is based on a string describing the inline method name and action names that the filter shall or shall not apply to.

filter() method
public void filter(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

Performs the filtering. This method calls the filter method defined in the controller class.


CForm

Package | system.web.form
Inheritance | class CForm » CFormElement » CComponent
Implements | ArrayAccess
Since | 1.1
Version | $Id: CForm.php 1850 2010-03-01 15:57:53Z qiang.xue $
CForm represents a form object that contains form input specifications.

The main purpose of introducing the abstraction of form objects is to enhance the reusability of forms. In particular, we can divide a form in two parts: those that specify each individual form inputs, and those that decorate the form inputs. A CForm object represents the former part. It relies on the rendering process to accomplish form input decoration. Reusability is mainly achieved in the rendering process. That is, a rendering process can be reused to render different CForm objects.

A form can be rendered in different ways. One can call the render method to get a quick form rendering without writing any HTML code; one can also override render to render the form in a different layout; and one can use an external view template to render each form element explicitly. In these ways, the render method can be applied to all kinds of forms and thus achieves maximum reusability; while the external view template keeps maximum flexibility in rendering complex forms.

Form input specifications are organized in terms of a form element hierarchy. At the root of the hierarchy, it is the root CForm object. The root form object maintains its children in two collections: elements and buttons. The former contains non-button form elements (CFormStringElement, CFormInputElement and CForm); while the latter mainly contains button elements (CFormButtonElement). When a CForm object is embedded in the elements collection, it is called a sub-form which can have its own elements and buttons collections and thus form the whole form hierarchy.

Sub-forms are mainly used to handle multiple models. For example, in a user registration form, we can have the root form to collect input for the user table while a sub-form to collect input for the profile table. Sub-form is also a good way to partition a lengthy form into shorter ones, even though all inputs may belong to the same model.

Form input specifications are given in terms of a configuration array which is used to initialize the property values of a CForm object. The elements and buttons properties need special attention as they are the main properties to be configured. To configure elements, we should give it an array like the following:
'elements'=>array(
    'username'=>array('type'=>'text', 'maxlength'=>80),
    'password'=>array('type'=>'password', 'maxlength'=>80),
)
The above code specifies two input elements: 'username' and 'password'. Note the model object must have exactly the same attributes 'username' and 'password'. Each element has a type which specifies what kind of input should be used. The rest of the array elements (e.g. 'maxlength') in an input specification are rendered as HTML element attributes when the input field is rendered. The buttons property is configured similarly.

For more details about configuring form elements, please refer to CFormInputElement and CFormButtonElement.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
action | mixed | the form action URL (see CHtml::normalizeUrl for details about this parameter. | CForm
activeForm | array | the configuration used to create the active form widget. | CForm
activeFormWidget | CActiveForm | the active form widget associated with this form. | CForm
attributes | array | HTML attribute values for the form tag. | CFormElement
buttonElementClass | string | the name of the class for representing a form button element. | CForm
buttons | CFormElementCollection | Returns the button elements of this form. | CForm
description | string | the description of this form. | CForm
elements | CFormElementCollection | Returns the input elements of this form. | CForm
inputElementClass | string | the name of the class for representing a form input element. | CForm
method | string | the submission method of this form. | CForm
model | CModel | Returns the model that this form is associated with. | CForm
models | array | Returns all models that are associated with this form or its sub-forms. | CForm
owner | CBaseController | the owner of this form. | CForm
parent | mixed | the direct parent of this element. | CFormElement
root | CForm | the top-level form object | CForm
showErrorSummary | boolean | whether to show error summary. | CForm
title | string | the title for this form. | CForm
visible | boolean | Returns a value indicating whether this element is visible and should be rendered. | CFormElement

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
uniqueId | string | Returns a unique ID that identifies this form in the current page. | CForm

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CForm
__get() | Returns a property value or an attribute value. | CFormElement
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a property or attribute. | CFormElement
__toString() | Converts the object to a string. | CFormElement
__unset() | Sets a component property to be null. | CComponent
addedElement() | This method is called after an element is added to the element collection. | CForm
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clicked() | Returns a value indicating whether the specified button is clicked. | CForm
configure() | Configures this object with property initial values. | CFormElement
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getActiveFormWidget() |  | CForm
getButtons() | Returns the button elements of this form. | CForm
getElements() | Returns the input elements of this form. | CForm
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getModel() | Returns the model that this form is associated with. | CForm
getModels() | Returns all models that are associated with this form or its sub-forms. | CForm
getOwner() |  | CForm
getParent() |  | CFormElement
getRoot() |  | CForm
getVisible() | Returns a value indicating whether this element is visible and should be rendered. | CFormElement
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
loadData() | Loads the submitted data into the associated model(s) to the form. | CForm
offsetExists() | Returns whether there is an element at the specified offset. | CForm
offsetGet() | Returns the element at the specified offset. | CForm
offsetSet() | Sets the element at the specified offset. | CForm
offsetUnset() | Unsets the element at the specified offset. | CForm
raiseEvent() | Raises an event. | CComponent
removedElement() | This method is called after an element is removed from the element collection. | CForm
render() | Renders the form. | CForm
renderBegin() | Renders the open tag of the form. | CForm
renderBody() | Renders the body content of this form. | CForm
renderButtons() | Renders the buttons in this form. | CForm
renderElement() | Renders a single element which could be an input element, a sub-form, a string, or a button. | CForm
renderElements() | Renders the elements in this form. | CForm
renderEnd() | Renders the close tag of the form. | CForm
setButtons() | Configures the buttons of this form. | CForm
setElements() | Configures the input elements of this form. | CForm
setModel() |  | CForm
setVisible() |  | CFormElement
submitted() | Returns a value indicating whether this form is submitted. | CForm
validate() | Validates the models associated with this form. | CForm

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluateVisible() | Evaluates the visibility of this form. | CForm
getUniqueId() | Returns a unique ID that identifies this form in the current page. | CForm
init() | Initializes this form. | CForm

Property Details

action property
public mixed $action;

the form action URL (see CHtml::normalizeUrl for details about this parameter.) Defaults to an empty string, meaning the current request URL. This property is ignored when this form is a sub-form.

activeForm property (available since v1.1.1)
public array $activeForm;

the configuration used to create the active form widget. The widget will be used to render the form tag and the error messages. The 'class' option is required, which specifies the class of the widget. The rest of the options will be passed to CBaseController::beginWidget() call. Defaults to array('class'=>'CActiveForm').

activeFormWidget property read-only (available since v1.1.1)
public CActiveForm getActiveFormWidget()

the active form widget associated with this form. This method will return the active form widget as specified by activeForm.

buttonElementClass property
public string $buttonElementClass;

the name of the class for representing a form button element. Defaults to 'CFormButtonElement'.

buttons property
public CFormElementCollection getButtons()
public void setButtons(array $buttons)

Returns the button elements of this form. Note that the returned result is a CFormElementCollection object, which means you can use it like an array. For more details, see CMap.

description property
public string $description;

the description of this form.

elements property
public CFormElementCollection getElements()
public void setElements(array $elements)

Returns the input elements of this form. This includes text strings, input elements and sub-forms. Note that the returned result is a CFormElementCollection object, which means you can use it like an array. For more details, see CMap.

inputElementClass property
public string $inputElementClass;

the name of the class for representing a form input element. Defaults to 'CFormInputElement'.

method property
public string $method;

the submission method of this form. Defaults to 'post'. This property is ignored when this form is a sub-form.

model property
public CModel getModel(boolean $checkParent=true)
public void setModel(CModel $model)

Returns the model that this form is associated with.

models property read-only
public array getModels()

Returns all models that are associated with this form or its sub-forms.

owner property read-only
public CBaseController getOwner()

the owner of this form. This refers to either a controller or a widget by which the form is created and rendered.

root property read-only
public CForm getRoot()

the top-level form object

showErrorSummary property
public boolean $showErrorSummary;

whether to show error summary. Defaults to false.

title property
public string $title;

the title for this form. By default, if this is set, a fieldset may be rendered around the form body using the title as its legend. Defaults to null.

uniqueId property read-only
protected string getUniqueId()

Returns a unique ID that identifies this form in the current page.

Method Details

__construct() method
public void __construct(mixed $config, CModel $model=NULL, mixed $parent=NULL)
$config | mixed | the configuration for this form. It can be a configuration array or the path alias of a PHP script file that returns a configuration array. The configuration array consists of name-value pairs that are used to initialize the properties of this form.
$model | CModel | the model object associated with this form. If it is null, the parent's model will be used instead.
$parent | mixed | the direct parent of this form. This could be either a CBaseController object (a controller or a widget), or a CForm object. If the former, it means the form is a top-level form; if the latter, it means this form is a sub-form.

Constructor. If you override this method, make sure you do not modify the method signature, and also make sure you call the parent implementation.

addedElement() method
public void addedElement(string $name, CFormElement $element, boolean $forButtons)
$name | string | the name of the element
$element | CFormElement | the element that is added
$forButtons | boolean | whether the element is added to the buttons collection. If false, it means the element is added to the elements collection.

This method is called after an element is added to the element collection.

clicked() method
public boolean clicked(string $name)
$name | string | the button name
{return} | boolean | whether the button is clicked.

Returns a value indicating whether the specified button is clicked.

evaluateVisible() method
protected boolean evaluateVisible()
{return} boolean whether this form is visible.

Evaluates the visibility of this form. This method will check the visibility of the elements. If any one of them is visible, the form is considered as visible. Otherwise, it is invisible.

getActiveFormWidget() method (available since v1.1.1)
public CActiveForm getActiveFormWidget()
{return} CActiveForm the active form widget associated with this form. This method will return the active form widget as specified by activeForm.

getButtons() method
public CFormElementCollection getButtons()
{return} CFormElementCollection the form elements.

Returns the button elements of this form. Note that the returned result is a CFormElementCollection object, which means you can use it like an array. For more details, see CMap.

getElements() method
public CFormElementCollection getElements()
{return} CFormElementCollection the form elements.

Returns the input elements of this form. This includes text strings, input elements and sub-forms. Note that the returned result is a CFormElementCollection object, which means you can use it like an array. For more details, see CMap.

getModel() method
public CModel getModel(boolean $checkParent=true)
$checkParent | boolean | whether to return parent's model if this form doesn't have model by itself.
{return} | CModel | the model associated with this form. If this form does not have a model, it will look for a model in its ancestors.

Returns the model that this form is associated with.

getModels() method
public array getModels()
{return} array the models that are associated with this form or its sub-forms.

Returns all models that are associated with this form or its sub-forms.

getOwner() method
public CBaseController getOwner()
{return} CBaseController the owner of this form. This refers to either a controller or a widget by which the form is created and rendered.

getRoot() method
public CForm getRoot()
{return} CForm the top-level form object

getUniqueId() method
protected string getUniqueId()
{return} string the unique ID identifying this form

Returns a unique ID that identifies this form in the current page.

init() method
protected void init()

Initializes this form. This method is invoked at the end of the constructor. You may override this method to provide customized initialization (such as configuring the form object).

loadData() method
public void loadData()

Loads the submitted data into the associated model(s) to the form. This method will go through all models associated with this form and its sub-forms and massively assign the submitted data to the models.

See Also

  • submitted
offsetExists() method
public boolean offsetExists(mixed $offset)
$offset | mixed | the offset to check on
{return} | boolean |

Returns whether there is an element at the specified offset. This method is required by the interface ArrayAccess.

offsetGet() method
public mixed offsetGet(integer $offset)
$offset | integer | the offset to retrieve element.
{return} | mixed | the element at the offset, null if no element is found at the offset

Returns the element at the specified offset. This method is required by the interface ArrayAccess.

offsetSet() method
public void offsetSet(integer $offset, mixed $item)
$offset | integer | the offset to set element
$item | mixed | the element value

Sets the element at the specified offset. This method is required by the interface ArrayAccess.

offsetUnset() method
public void offsetUnset(mixed $offset)
$offset mixed the offset to unset element

Unsets the element at the specified offset. This method is required by the interface ArrayAccess.

removedElement() method
public void removedElement(string $name, CFormElement $element, boolean $forButtons)
$name | string | the name of the element
$element | CFormElement | the element that is removed
$forButtons | boolean | whether the element is removed from the buttons collection If false, it means the element is removed from the elements collection.

This method is called after an element is removed from the element collection.

render() method
public string render()
{return} string the rendering result

Renders the form. The default implementation simply calls renderBegin, renderBody and renderEnd.

renderBegin() method
public string renderBegin()
{return} string the rendering result

Renders the open tag of the form. The default implementation will render the open form tag. If title or description is specified, they will be rendered as well. And if the associated model contains error, the error summary may also be displayed.

renderBody() method
public string renderBody()
{return} string the rendering result

Renders the body content of this form. This method mainly renders elements and buttons. The form tag will not be rendered. Please call renderBegin and renderEnd to render the open and close tags of the form. You may override this method to customize the rendering of the form.

renderButtons() method
public string renderButtons()
{return} string the rendering result

Renders the buttons in this form.

renderElement() method
public string renderElement(mixed $element)
$element | mixed | the form element to be rendered. This can be either a CFormElement instance or a string representing the name of the form element.
{return} | string | the rendering result

Renders a single element which could be an input element, a sub-form, a string, or a button.

renderElements() method
public string renderElements()
{return} string the rendering result

Renders the elements in this form.

renderEnd() method
public string renderEnd()
{return} string the rendering result

Renders the close tag of the form.

setButtons() method
public void setButtons(array $buttons)
$buttons array the button configurations

Configures the buttons of this form. The configuration must be an array of button configuration array indexed by button name. Each button configuration array consists of name-value pairs that are used to initialize a CFormButtonElement object.

setElements() method
public void setElements(array $elements)
$elements array the button configurations

Configures the input elements of this form. The configuration must be an array of input configuration array indexed by input name. Each input configuration array consists of name-value pairs that are used to initialize a CFormStringElement object (when 'type' is 'string'), a CFormElement object (when 'type' is a string ending with 'Form'), or a CFormInputElement object in all other cases.

setModel() method
public void setModel(CModel $model)
$model CModel the model to be associated with this form

submitted() method
public boolean submitted(string $buttonName='submit', boolean $loadData=true)
$buttonName | string | the name of the submit button
$loadData | boolean | whether to call loadData if the form is submitted so that the submitted data can be populated to the associated models.
{return} | boolean | whether this form is submitted.

Returns a value indicating whether this form is submitted.

See Also

  • loadData
validate() method
public boolean validate()
{return} boolean whether all models are valid

Validates the models associated with this form. All models, including those associated with sub-forms, will perform the validation. You may use CModel::getErrors() to retrieve the validation error messages.


CFormButtonElement

Package | system.web.form
Inheritance | class CFormButtonElement » CFormElement » CComponent
Since | 1.1
Version | $Id: CFormButtonElement.php 1820 2010-02-19 03:03:01Z qiang.xue $
CFormButtonElement represents a form button element.

CFormButtonElement can represent the following types of button based on type property:
  • htmlButton: a normal button generated using CHtml::htmlButton
  • htmlReset a reset button generated using CHtml::htmlButton
  • htmlSubmit: a submit button generated using CHtml::htmlButton
  • submit: a submit button generated using CHtml::submitButton
  • button: a normal button generated using CHtml::button
  • image: an image button generated using CHtml::imageButton
  • reset: a reset button generated using CHtml::resetButton
  • link: a link button generated using CHtml::linkButton
The type property can also be a class name or a path alias to the class. In this case, the button is generated using a widget of the specified class. Note, the widget must have a property called "name".

Because CFormElement is an ancestor class of CFormButtonElement, a value assigned to a non-existing property will be stored in attributes which will be passed as HTML attribute values to the CHtml method generating the button or initial values of the widget properties.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes (name=>value) for the HTML element represented by this object. | CFormElement
coreTypes | array | Core button types (alias=>CHtml method name) | CFormButtonElement
label | string | the label of this button. | CFormButtonElement
name | string | name of this button | CFormButtonElement
on | string | Returns a value indicating under which scenarios this button is visible. | CFormButtonElement
parent | mixed | the direct parent of this element. | CFormElement
type | string | the type of this button. | CFormButtonElement
visible | boolean | Returns a value indicating whether this element is visible and should be rendered. | CFormElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormElement
__get() | Returns a property value or an attribute value. | CFormElement
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a property or attribute. | CFormElement
__toString() | Converts the object to a string. | CFormElement
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures this object with property initial values. | CFormElement
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOn() | Returns a value indicating under which scenarios this button is visible. | CFormButtonElement
getParent() |  | CFormElement
getVisible() | Returns a value indicating whether this element is visible and should be rendered. | CFormElement
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
render() | Returns this button. | CFormButtonElement
setOn() |  | CFormButtonElement
setVisible() |  | CFormElement

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluateVisible() | Evaluates the visibility of this element. | CFormButtonElement

Property Details

coreTypes property
public static array $coreTypes;

Core button types (alias=>CHtml method name)

label property
public string $label;

the label of this button. This property is ignored when a widget is used to generate the button.

name property
public string $name;

name of this button

on property
public string getOn()
public void setOn(string $value)

Returns a value indicating under which scenarios this button is visible. If the value is empty, it means the button is visible under all scenarios. Otherwise, only when the model is in the scenario whose name can be found in this value, will the button be visible. See CModel::scenario for more information about model scenarios.

type property
public string $type;

the type of this button. This can be a class name, a path alias of a class name, or a button type alias (submit, button, image, reset, link, htmlButton, htmlSubmit, htmlReset).

Method Details

evaluateVisible() method
protected boolean evaluateVisible()
{return} boolean whether this element is visible.

Evaluates the visibility of this element. This method will check the on property to see if the model is in a scenario that should have this string displayed.

getOn() method
public string getOn()
{return} string scenario names separated by commas. Defaults to null.

Returns a value indicating under which scenarios this button is visible. If the value is empty, it means the button is visible under all scenarios. Otherwise, only when the model is in the scenario whose name can be found in this value, will the button be visible. See CModel::scenario for more information about model scenarios.

render() method
public string render()
{return} string the rendering result

Returns this button.

setOn() method
public void setOn(string $value)
$value string scenario names separated by commas.


CFormElement

Package | system.web.form
Inheritance | abstract class CFormElement » CComponent
Subclasses | CForm, CFormButtonElement, CFormInputElement, CFormStringElement
Since | 1.1
Version | $Id: CFormElement.php 1820 2010-02-19 03:03:01Z qiang.xue $
CFormElement is the base class for presenting all kinds of form element.

CFormElement implements the way to get and set arbitrary attributes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes (name=>value) for the HTML element represented by this object. | CFormElement
parent | mixed | the direct parent of this element. | CFormElement
visible | boolean | Returns a value indicating whether this element is visible and should be rendered. | CFormElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormElement
__get() | Returns a property value or an attribute value. | CFormElement
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a property or attribute. | CFormElement
__toString() | Converts the object to a string. | CFormElement
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures this object with property initial values. | CFormElement
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getParent() |  | CFormElement
getVisible() | Returns a value indicating whether this element is visible and should be rendered. | CFormElement
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
render() | Renders this element. | CFormElement
setVisible() |  | CFormElement

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluateVisible() | Evaluates the visibility of this element. | CFormElement

Property Details

attributes property
public array $attributes;

list of attributes (name=>value) for the HTML element represented by this object.

parent property read-only
public mixed getParent()

the direct parent of this element. This could be either a CForm object or a CBaseController object (a controller or a widget).

visible property
public boolean getVisible()
public void setVisible(boolean $value)

Returns a value indicating whether this element is visible and should be rendered. This method will call evaluateVisible to determine the visibility of this element.

Method Details

__construct() method
public void __construct(mixed $config, mixed $parent)
$config | mixed | the configuration for this element.
$parent | mixed | the direct parent of this element.

Constructor.

See Also

  • configure
__get() method
public mixed __get(string $name)
$name | string | the property or attribute name
{return} | mixed | the property or attribute value

Returns a property value or an attribute value. Do not call this method. This is a PHP magic method that we override to allow using the following syntax to read a property or attribute:

$value=$element->propertyName;
$value=$element->attributeName;

See Also

  • __set
__set() method
public void __set(string $name, mixed $value)
$name | string | the property or attribute name
$value | mixed | the property or attribute value

Sets value of a property or attribute. Do not call this method. This is a PHP magic method that we override to allow using the following syntax to set a property or attribute.

$this->propertyName=$value;
$this->attributeName=$value;

See Also

  • __get
__toString() method
public string __toString()
{return} string the string representation of this object.

Converts the object to a string. This is a PHP magic method. The default implementation simply calls render and return the rendering result.

configure() method
public void configure(mixed $config)
$config mixed the configuration for this object. This can be an array representing the property names and their initial values. It can also be a string representing the file name of the PHP script that returns a configuration array.

Configures this object with property initial values.

evaluateVisible() method
protected boolean evaluateVisible()
{return} boolean whether this element is visible. Defaults to true.

Evaluates the visibility of this element. Child classes should override this method to implement the actual algorithm for determining the visibility.

getParent() method
public mixed getParent()
{return} mixed the direct parent of this element. This could be either a CForm object or a CBaseController object (a controller or a widget).

getVisible() method
public boolean getVisible()
{return} boolean whether this element is visible and should be rendered.

Returns a value indicating whether this element is visible and should be rendered. This method will call evaluateVisible to determine the visibility of this element.

render() method
abstract public string render()
{return} string the rendering result

Renders this element.

setVisible() method
public void setVisible(boolean $value)
$value boolean whether this element is visible and should be rendered.


CFormElementCollection

Package | system.web.form
Inheritance | class CFormElementCollection » CMap » CComponent
Implements | Countable, ArrayAccess, Traversable, IteratorAggregate
Since | 1.1
Version | $Id: CFormElementCollection.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFormElementCollection implements the collection for storing form elements.

Because CFormElementCollection extends from CMap, it can be used like an associative array. For example,
$element=$collection['username'];
$collection['username']=array('type'=>'text', 'maxlength'=>128);
$collection['password']=new CFormInputElement(array('type'=>'password'),$form);
$collection[]='some string';

CFormElementCollection can store three types of value: a configuration array, a CFormElement object, or a string, as shown in the above example. Internally, these values will be converted to CFormElement objects.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
count | integer | the number of items in the map | CMap
iterator | CMapIterator | Returns an iterator for traversing the items in the list. | CMap
keys | array | the key list | CMap
readOnly | boolean | whether this map is read-only or not. | CMap

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormElementCollection
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
add() | Adds an item to the collection. | CFormElementCollection
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
clear() | Removes all items in the map. | CMap
contains() |  | CMap
copyFrom() | Copies iterable data into the map. | CMap
count() | Returns the number of items in the map. | CMap
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getCount() |  | CMap
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIterator() | Returns an iterator for traversing the items in the list. | CMap
getKeys() |  | CMap
getReadOnly() |  | CMap
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
itemAt() | Returns the item with the specified key. | CMap
mergeArray() | Merges two arrays into one recursively. | CMap
mergeWith() | Merges iterable data into the map. | CMap
offsetExists() | Returns whether there is an element at the specified offset. | CMap
offsetGet() | Returns the element at the specified offset. | CMap
offsetSet() | Sets the element at the specified offset. | CMap
offsetUnset() | Unsets the element at the specified offset. | CMap
raiseEvent() | Raises an event. | CComponent
remove() | Removes the specified element by key. | CFormElementCollection
toArray() |  | CMap

Protected Methods

Hide inherited methods

Method | Description | Defined By
setReadOnly() |  | CMap

Method Details

__construct() method
public void __construct(CForm $form, boolean $forButtons=false)
$form | CForm | the form object that owns this collection
$forButtons | boolean | whether this collection is used to store buttons.

Constructor.

add() method
public void add(mixed $key, mixed $value)
$key | mixed | key
$value | mixed | value

Adds an item to the collection. This method overrides the parent implementation to ensure only configuration arrays, strings, or CFormElement objects can be stored in this collection.

remove() method
public void remove(string $key)
$key string the name of the element to be removed from the collection

Removes the specified element by key.


CFormInputElement

Package | system.web.form
Inheritance | class CFormInputElement » CFormElement » CComponent
Since | 1.1
Version | $Id: CFormInputElement.php 1896 2010-03-13 14:11:24Z qiang.xue $
CFormInputElement represents form input element.

CFormInputElement can represent the following types of form input based on type property:
  • text: a normal text input generated using CHtml::activeTextField
  • hidden: a hidden input generated using CHtml::activeHiddenField
  • password: a password input generated using CHtml::activePasswordField
  • textarea: a text area generated using CHtml::activeTextArea
  • file: a file input generated using CHtml::activeFileField
  • radio: a radio button generated using CHtml::activeRadioButton
  • checkbox: a check box generated using CHtml::activeCheckBox
  • listbox: a list box generated using CHtml::activeListBox
  • dropdownlist: a drop-down list generated using CHtml::activeDropDownList
  • checkboxlist: a list of check boxes generated using CHtml::activeCheckBoxList
  • radiolist: a list of radio buttons generated using CHtml::activeRadioButtonList
The type property can also be a class name or a path alias to the class. In this case, the input is generated using a widget of the specified class. Note, the widget must have a property called "model" which expects a model object, and a property called "attribute" which expects the name of a model attribute.

Because CFormElement is an ancestor class of CFormInputElement, a value assigned to a non-existing property will be stored in attributes which will be passed as HTML attribute values to the CHtml method generating the input or initial values of the widget properties.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes (name=>value) for the HTML element represented by this object. | CFormElement
coreTypes | array | Core input types (alias=>CHtml method name) | CFormInputElement
errorOptions | array | the options used when rendering the error part. | CFormInputElement
hint | string | hint text of this input | CFormInputElement
items | array | the options for this input when it is a list box, drop-down list, check box list, or radio button list. | CFormInputElement
label | string | the label for this input. | CFormInputElement
layout | string | the layout used to render label, input, hint and error. | CFormInputElement
name | string | name of this input | CFormInputElement
parent | mixed | the direct parent of this element. | CFormElement
required | boolean | Gets the value indicating whether this input is required. | CFormInputElement
type | string | the type of this input. | CFormInputElement
visible | boolean | Returns a value indicating whether this element is visible and should be rendered. | CFormElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormElement
__get() | Returns a property value or an attribute value. | CFormElement
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a property or attribute. | CFormElement
__toString() | Converts the object to a string. | CFormElement
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures this object with property initial values. | CFormElement
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getLabel() |  | CFormInputElement
getParent() |  | CFormElement
getRequired() | Gets the value indicating whether this input is required. | CFormInputElement
getVisible() | Returns a value indicating whether this element is visible and should be rendered. | CFormElement
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
render() | Renders everything for this input. | CFormInputElement
renderError() | Renders the error display of this input. | CFormInputElement
renderHint() | Renders the hint text for this input. | CFormInputElement
renderInput() | Renders the input field. | CFormInputElement
renderLabel() | Renders the label for this input. | CFormInputElement
setLabel() |  | CFormInputElement
setRequired() |  | CFormInputElement
setVisible() |  | CFormElement

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluateVisible() | Evaluates the visibility of this element. | CFormInputElement

Property Details

coreTypes property
public static array $coreTypes;

Core input types (alias=>CHtml method name)

errorOptions property (available since v1.1.1)
public array $errorOptions;

the options used when rendering the error part. This property will be passed to the CActiveForm::error method call.

See Also

  • CActiveForm::error
hint property
public string $hint;

hint text of this input

items property
public array $items;

the options for this input when it is a list box, drop-down list, check box list, or radio button list. Please see CHtml::listData for details of generating this property value.

label property
public string getLabel()
public void setLabel(string $value)

the label for this input. If the label is not manually set, this method will call CModel::getAttributeLabel to determine the label.

layout property
public string $layout;

the layout used to render label, input, hint and error. They correspond to the placeholders "{label}", "{input}", "{hint}" and "{error}".

name property
public string $name;

name of this input

required property
public boolean getRequired()
public void setRequired(boolean $value)

Gets the value indicating whether this input is required. If this property is not set explicitly, it will be determined by calling CModel::isAttributeRequired for the associated model and attribute of this input.

type property
public string $type;

the type of this input. This can be a widget class name, a path alias of a widget class name, or a input type alias (text, hidden, password, textarea, file, radio, checkbox, listbox, dropdownlist, checkboxlist, or radiolist). If a widget class, it must extend from CInputWidget.

Method Details

evaluateVisible() method
protected boolean evaluateVisible()
{return} boolean whether this element is visible.

Evaluates the visibility of this element. This method will check if the attribute associated with this input is safe for the current model scenario.

getLabel() method
public string getLabel()
{return} string the label for this input. If the label is not manually set, this method will call CModel::getAttributeLabel to determine the label.

getRequired() method
public boolean getRequired()
{return} boolean whether this input is required.

Gets the value indicating whether this input is required. If this property is not set explicitly, it will be determined by calling CModel::isAttributeRequired for the associated model and attribute of this input.

render() method
public string render()
{return} string the complete rendering result for this input, including label, input field, hint, and error.

Renders everything for this input. The default implementation simply returns the result of renderLabel, renderInput, renderHint. When CForm::showErrorSummary is false, renderError is also called to show error messages after individual input fields.

renderError() method
public string renderError()
{return} string the rendering result

Renders the error display of this input. The default implementation returns the result of CHtml::error

renderHint() method
public string renderHint()
{return} string the rendering result.

Renders the hint text for this input. The default implementation returns the hint property enclosed in a paragraph HTML tag.

renderInput() method
public string renderInput()
{return} string the rendering result

Renders the input field. The default implementation returns the result of the appropriate CHtml method or the widget.

renderLabel() method
public string renderLabel()
{return} string the rendering result

Renders the label for this input. The default implementation returns the result of activeLabelEx.

setLabel() method
public void setLabel(string $value)
$value string the label for this input

setRequired() method
public void setRequired(boolean $value)
$value boolean whether this input is required.


CFormStringElement

Package | system.web.form
Inheritance | class CFormStringElement » CFormElement » CComponent
Since | 1.1
Version | $Id: CFormStringElement.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFormStringElement represents a string in a form.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
attributes | array | list of attributes (name=>value) for the HTML element represented by this object. | CFormElement
content | string | the string content | CFormStringElement
on | string | Returns a value indicating under which scenarios this string is visible. | CFormStringElement
parent | mixed | the direct parent of this element. | CFormElement
visible | boolean | Returns a value indicating whether this element is visible and should be rendered. | CFormElement

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFormElement
__get() | Returns a property value or an attribute value. | CFormElement
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a property or attribute. | CFormElement
__toString() | Converts the object to a string. | CFormElement
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
configure() | Configures this object with property initial values. | CFormElement
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOn() | Returns a value indicating under which scenarios this string is visible. | CFormStringElement
getParent() |  | CFormElement
getVisible() | Returns a value indicating whether this element is visible and should be rendered. | CFormElement
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
render() | Renders this element. | CFormStringElement
setOn() |  | CFormStringElement
setVisible() |  | CFormElement

Protected Methods

Hide inherited methods

Method | Description | Defined By
evaluateVisible() | Evaluates the visibility of this element. | CFormStringElement

Property Details

content property
public string $content;

the string content

on property
public string getOn()
public void setOn(string $value)

Returns a value indicating under which scenarios this string is visible. If the value is empty, it means the string is visible under all scenarios. Otherwise, only when the model is in the scenario whose name can be found in this value, will the string be visible. See CModel::scenario for more information about model scenarios.

Method Details

evaluateVisible() method
protected boolean evaluateVisible()
{return} boolean whether this element is visible.

Evaluates the visibility of this element. This method will check the on property to see if the model is in a scenario that should have this string displayed.

getOn() method
public string getOn()
{return} string scenario names separated by commas. Defaults to null.

Returns a value indicating under which scenarios this string is visible. If the value is empty, it means the string is visible under all scenarios. Otherwise, only when the model is in the scenario whose name can be found in this value, will the string be visible. See CModel::scenario for more information about model scenarios.

render() method
public string render()
{return} string the string content

Renders this element. The default implementation simply returns content.

setOn() method
public void setOn(string $value)
$value string scenario names separated by commas.


CGoogleApi

All Packages | Methods
Package | system.web.helpers
Inheritance | class CGoogleApi
Since | 1.0.3
Version | $Id: CGoogleApi.php 1678 2010-01-07 21:02:00Z qiang.xue $
CGoogleApi provides helper methods to easily access Google AJAX APIs.

Public Methods

Hide inherited methods

Method | Description | Defined By
init() | Renders the jsapi script file. | CGoogleApi
load() | Loads the specified API module. | CGoogleApi
register() | Registers the specified API module. | CGoogleApi

Method Details

init() method
public static string init(string $apiKey=NULL)
$apiKey | string | the API key. Null if you do not have a key.
{return} | string | the script tag that loads Google jsapi.

Renders the jsapi script file.

load() method
public static string load(string $name, string $version='1', array $options=array ( ))
$name | string | the module name
$version | string | the module version
$options | array | additional js options that are to be passed to the load() function.
{return} | string | the js code for loading the module. You can use CHtml::script() to enclose it in a script tag.

Loads the specified API module. Note that you should call init first.

register() method
public static void register(string $name, string $version='1', array $options=array ( ), string $apiKey=NULL)
$name | string | the module name
$version | string | the module version
$options | array | additional js options that are to be passed to the load() function.
$apiKey | string | the API key. Null if you do not have a key.

Registers the specified API module. This is similar to load except that it registers the loading code with CClientScript instead of returning it. This method also registers the jsapi script needed by the loading call.


CHtml

Package | system.web.helpers
Inheritance | class CHtml
Since | 1.0
Version | $Id: CHtml.php 1863 2010-03-07 13:26:05Z qiang.xue $
CHtml is a static class that provides a collection of helper methods for creating HTML views.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
afterRequiredLabel | string | the HTML code to be appended to the required label. | CHtml
beforeRequiredLabel | string | the HTML code to be prepended to the required label. | CHtml
count | integer | the counter for generating automatic input field names. | CHtml
errorCss | string | the CSS class for highlighting error inputs. | CHtml
errorMessageCss | string | the CSS class for displaying error messages (see error). | CHtml
errorSummaryCss | string | the CSS class for displaying error summaries (see errorSummary). | CHtml
requiredCss | string | the CSS class for required labels. | CHtml

Public Methods

Hide inherited methods

Method | Description | Defined By
activeCheckBox() | Generates a check box for a model attribute. | CHtml
activeCheckBoxList() | Generates a check box list for a model attribute. | CHtml
activeDropDownList() | Generates a drop down list for a model attribute. | CHtml
activeFileField() | Generates a file input for a model attribute. | CHtml
activeHiddenField() | Generates a hidden input for a model attribute. | CHtml
activeId() | Generates input field ID for a model attribute. | CHtml
activeLabel() | Generates a label tag for a model attribute. | CHtml
activeLabelEx() | Generates a label tag for a model attribute. | CHtml
activeListBox() | Generates a list box for a model attribute. | CHtml
activeName() | Generates input field name for a model attribute. | CHtml
activePasswordField() | Generates a password field input for a model attribute. | CHtml
activeRadioButton() | Generates a radio button for a model attribute. | CHtml
activeRadioButtonList() | Generates a radio button list for a model attribute. | CHtml
activeTextArea() | Generates a text area input for a model attribute. | CHtml
activeTextField() | Generates a text field input for a model attribute. | CHtml
ajax() | Generates the JavaScript that initiates an AJAX request. | CHtml
ajaxButton() | Generates a push button that can initiate AJAX requests. | CHtml
ajaxLink() | Generates a link that can initiate AJAX requests. | CHtml
ajaxSubmitButton() | Generates a push button that can submit the current form in POST method. | CHtml
asset() | Generates the URL for the published assets. | CHtml
beginForm() | Generates an opening form tag. | CHtml
button() | Generates a button. | CHtml
cdata() | Encloses the given string within a CDATA tag. | CHtml
checkBox() | Generates a check box. | CHtml
checkBoxList() | Generates a check box list. | CHtml
closeTag() | Generates a close HTML element. | CHtml
css() | Encloses the given CSS content with a CSS tag. | CHtml
cssFile() | Links to the specified CSS file. | CHtml
dropDownList() | Generates a drop down list. | CHtml
encode() | Encodes special characters into HTML entities. | CHtml
encodeArray() | Encodes special characters in an array of strings into HTML entities. | CHtml
endForm() | Generates a closing form tag. | CHtml
error() | Displays the first validation error for a model attribute. | CHtml
errorSummary() | Displays a summary of validation errors for one or several models. | CHtml
fileField() | Generates a file input. | CHtml
form() | Generates an opening form tag. | CHtml
getActiveId() | Returns the element ID that is used by methods such as activeTextField. | CHtml
getIdByName() | Generates a valid HTML ID based the name. | CHtml
hiddenField() | Generates a hidden input. | CHtml
htmlButton() | Generates a button using HTML button tag. | CHtml
image() | Generates an image tag. | CHtml
imageButton() | Generates an image submit button. | CHtml
label() | Generates a label tag. | CHtml
link() | Generates a hyperlink tag. | CHtml
linkButton() | Generates a link submit button. | CHtml
linkTag() | Generates a link tag that can be inserted in the head section of HTML page. | CHtml
listBox() | Generates a list box. | CHtml
listData() | Generates the data suitable for dropDownList and listBox. | CHtml
listOptions() | Generates the list options. | CHtml
mailto() | Generates a mailto link. | CHtml
metaTag() | Generates a meta tag that can be inserted in the head section of HTML page. | CHtml
normalizeUrl() | Normalizes the input parameter to be a valid URL. | CHtml
openTag() | Generates an open HTML element. | CHtml
pageStateField() | Generates a hidden field for storing persistent page states. | CHtml
passwordField() | Generates a password field input. | CHtml
radioButton() | Generates a radio button. | CHtml
radioButtonList() | Generates a radio button list. | CHtml
refresh() | Registers a 'refresh' meta tag. | CHtml
resetButton() | Generates a reset button. | CHtml
resolveName() | Generates input name for a model attribute. | CHtml
resolveNameID() | Generates input name and ID for a model attribute. | CHtml
script() | Encloses the given JavaScript within a script tag. | CHtml
scriptFile() | Includes a JavaScript file. | CHtml
statefulForm() | Generates a stateful form tag. | CHtml
submitButton() | Generates a submit button. | CHtml
tag() | Generates an HTML element. | CHtml
textArea() | Generates a text area input. | CHtml
textField() | Generates a text field input. | CHtml
value() | Evaluates the value of the specified attribute for the given model. | CHtml

Protected Methods

Hide inherited methods

Method | Description | Defined By
activeInputField() | Generates an input HTML tag for a model attribute. | CHtml
addErrorCss() | Appends errorCss to the 'class' attribute. | CHtml
clientChange() | Generates the JavaScript with the specified client changes. | CHtml
inputField() | Generates an input HTML tag. | CHtml
renderAttributes() | Renders the HTML tag attributes. | CHtml

Property Details

afterRequiredLabel property
public static string $afterRequiredLabel;

the HTML code to be appended to the required label.

See Also

  • label
beforeRequiredLabel property
public static string $beforeRequiredLabel;

the HTML code to be prepended to the required label.

See Also

  • label
count property (available since v1.0.4)
public static integer $count;

the counter for generating automatic input field names.

errorCss property
public static string $errorCss;

the CSS class for highlighting error inputs. Form inputs will be appended with this CSS class if they have input errors.

errorMessageCss property
public static string $errorMessageCss;

the CSS class for displaying error messages (see error).

errorSummaryCss property
public static string $errorSummaryCss;

the CSS class for displaying error summaries (see errorSummary).

requiredCss property
public static string $requiredCss;

the CSS class for required labels. Defaults to 'required'.

See Also

  • label

Method Details

activeCheckBox() method
public static string activeCheckBox(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) Since version 1.0.2, a special option named 'uncheckValue' is available that can be used to specify the value returned when the checkbox is not checked. By default, this value is '0'. Internally, a hidden field is rendered so that when the checkbox is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is set as NULL, the hidden field will not be rendered.
{return} | string | the generated check box

Generates a check box for a model attribute. The attribute is assumed to take either true or false value. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • activeInputField
activeCheckBoxList() method
public static string activeCheckBoxList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$data | array | value-label pairs used to generate the check box list. Note, the values will be automatically HTML-encoded, while the labels will not.
$htmlOptions array addtional HTML options. The options will be applied to each checkbox input. The following special options are recognized:
  • template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated check box input tag while "{label}" be replaced by the corresponding check box label.
  • separator: string, specifies the string that separates the generated check boxes.
  • checkAll: string, specifies the label for the "check all" checkbox. If this option is specified, a 'check all' checkbox will be displayed. Clicking on this checkbox will cause all checkboxes checked or unchecked. This option has been available since version 1.0.4.
  • checkAllLast: boolean, specifies whether the 'check all' checkbox should be displayed at the end of the checkbox list. If this option is not set (default) or is false, the 'check all' checkbox will be displayed at the beginning of the checkbox list. This option has been available since version 1.0.4.
  • encode: boolean, specifies whether to encode HTML-encode tag attributes and values. Defaults to true. This option has been available since version 1.0.5.
{return} | string | the generated check box list

Generates a check box list for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss. Note that a check box list allows multiple selection, like listBox. As a result, the corresponding POST value is an array. In case no selection is made, the corresponding POST value is an empty string.

See Also

  • checkBoxList
activeDropDownList() method
public static string activeDropDownList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method.
$htmlOptions array additional HTML attributes. Besides normal HTML attributes, a few special attributes are recognized. See clientChange and tag for more details. In addition, the following options are also supported:
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the 'empty' option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
        'value1'=>array('disabled'=>true, 'label'=>'value 1'),
        'value2'=>array('label'=>'value 2'),
    );
    This option has been available since version 1.0.3.
{return} | string | the generated drop down list

Generates a drop down list for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • listData
activeFileField() method
public static string activeFileField(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated input field

Generates a file input for a model attribute. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'. After the form is submitted, the uploaded file information can be obtained via $_FILES (see PHP documentation).

See Also

  • activeInputField
activeHiddenField() method
public static string activeHiddenField(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes.
{return} | string | the generated input field

Generates a hidden input for a model attribute.

See Also

  • activeInputField
activeId() method (available since v1.0.1)
public static string activeId(CModel $model, string $attribute)
$model | CModel | the data model
$attribute | string | the attribute
{return} | string | the generated input field ID

Generates input field ID for a model attribute.

activeInputField() method
protected static string activeInputField(string $type, CModel $model, string $attribute, array $htmlOptions)
$type | string | the input type (e.g. 'text', 'radio')
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes for the HTML tag
{return} | string | the generated input tag

Generates an input HTML tag for a model attribute. This method generates an input HTML tag based on the given data model and attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss. This enables highlighting the incorrect input.

activeLabel() method
public static string activeLabel(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions array additional HTML attributes. The following special options are recognized:
  • required: if this is set and is true, the label will be styled with CSS class 'required' (customizable with CHtml::$requiredCss), and be decorated with CHtml::beforeRequiredLabel and CHtml::afterRequiredLabel. This option has been available since version 1.0.2.
  • label: this specifies the label to be displayed. If this is not set, CModel::getAttributeLabel will be called to get the label for display. If the label is specified as false, no label will be rendered. This option has been available since version 1.0.4.
{return} | string | the generated label tag

Generates a label tag for a model attribute. The label text is the attribute label and the label is associated with the input for the attribute (see CModel::getAttributeLabel. If the attribute has input error, the label's CSS class will be appended with errorCss.

activeLabelEx() method (available since v1.0.2)
public static string activeLabelEx(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes.
{return} | string | the generated label tag

Generates a label tag for a model attribute. This is an enhanced version of activeLabel. It will render additional CSS class and mark when the attribute is required. In particular, it calls CModel::isAttributeRequired to determine if the attribute is required. If so, it will add a CSS class CHtml::requiredCss to the label, and decorate the label with CHtml::beforeRequiredLabel and CHtml::afterRequiredLabel.

activeListBox() method
public static string activeListBox(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method.
$htmlOptions array additional HTML attributes. Besides normal HTML attributes, a few special attributes are recognized. See clientChange and tag for more details. In addition, the following options are also supported:
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the 'empty' option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
        'value1'=>array('disabled'=>true, 'label'=>'value 1'),
        'value2'=>array('label'=>'value 2'),
    );
    This option has been available since version 1.0.3.
{return} | string | the generated list box

Generates a list box for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • listData
activeName() method (available since v1.0.1)
public static string activeName(CModel $model, string $attribute)
$model | CModel | the data model
$attribute | string | the attribute
{return} | string | the generated input field name

Generates input field name for a model attribute. Unlike resolveName, this method does NOT modify the attribute name.

activePasswordField() method
public static string activePasswordField(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated input field

Generates a password field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • activeInputField
activeRadioButton() method
public static string activeRadioButton(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) Since version 1.0.9, a special option named 'uncheckValue' is available that can be used to specify the value returned when the radiobutton is not checked. By default, this value is '0'. Internally, a hidden field is rendered so that when the radiobutton is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is set as NULL, the hidden field will not be rendered.
{return} | string | the generated radio button

Generates a radio button for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • activeInputField
activeRadioButtonList() method
public static string activeRadioButtonList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$data | array | value-label pairs used to generate the radio button list. Note, the values will be automatically HTML-encoded, while the labels will not.
$htmlOptions array addtional HTML options. The options will be applied to each checkbox input. The following special options are recognized:
  • template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated radio button input tag while "{label}" be replaced by the corresponding radio button label.
  • separator: string, specifies the string that separates the generated radio buttons.
  • encode: boolean, specifies whether to encode HTML-encode tag attributes and values. Defaults to true. This option has been available since version 1.0.5.
{return} | string | the generated radio button list

Generates a radio button list for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • radioButtonList
activeTextArea() method
public static string activeTextArea(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated text area

Generates a text area input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
activeTextField() method
public static string activeTextField(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated input field

Generates a text field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.

See Also

  • clientChange
  • activeInputField
addErrorCss() method
protected static void addErrorCss(array $htmlOptions)
$htmlOptions array HTML options to be modified

Appends errorCss to the 'class' attribute.

ajax() method
public static string ajax(array $options)
$options array AJAX options. The valid options are specified in the jQuery ajax documentation. The following special options are added for convenience:
  • update: string, specifies the selector whose HTML content should be replaced by the AJAX request result.
  • replace: string, specifies the selector whose target should be replaced by the AJAX request result.
Note, if you specify the 'success' option, the above options will be ignored.
{return} string the generated JavaScript

Generates the JavaScript that initiates an AJAX request.

See Also

  • http://docs.jquery.com/Ajax/jQuery.ajax#options
ajaxButton() method
public static string ajaxButton(string $label, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))
$label | string | the button label
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details.
$ajaxOptions | array | AJAX options (see ajax)
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button

Generates a push button that can initiate AJAX requests.

ajaxLink() method
public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))
$text | string | the link body (it will NOT be HTML-encoded.)
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details.
$ajaxOptions | array | AJAX options (see ajax)
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated link

Generates a link that can initiate AJAX requests.

See Also

  • normalizeUrl
  • ajax
ajaxSubmitButton() method
public static string ajaxSubmitButton(string $label, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))
$label | string | the button label
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details.
$ajaxOptions | array | AJAX options (see ajax)
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button

Generates a push button that can submit the current form in POST method.

asset() method
public static string asset(string $path, boolean $hashByName=false)
$path | string | the path of the asset to be published
$hashByName | boolean | whether the published directory should be named as the hashed basename. If false, the name will be the hashed dirname of the path being published. Defaults to false. Set true if the path being published is shared among different extensions.
{return} | string | the asset URL

Generates the URL for the published assets.

beginForm() method (available since v1.0.4)
public static string beginForm(mixed $action='', string $method='post', array $htmlOptions=array ( ))
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.)
$method | string | form method (e.g. post, get)
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated form tag.

Generates an opening form tag. Note, only the open tag is generated. A close tag should be placed manually at the end of the form.

See Also

  • endForm
button() method
public static string button(string $label='button', array $htmlOptions=array ( ))
$label | string | the button label
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates a button.

See Also

  • clientChange
cdata() method
public static string cdata(string $text)
$text | string | the string to be enclosed
{return} | string | the CDATA tag with the enclosed content.

Encloses the given string within a CDATA tag.

checkBox() method
public static string checkBox(string $name, boolean $checked=false, array $htmlOptions=array ( ))
$name | string | the input name
$checked | boolean | whether the check box is checked
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated check box

Generates a check box.

See Also

  • clientChange
  • inputField
checkBoxList() method
public static string checkBoxList(string $name, mixed $select, array $data, array $htmlOptions=array ( ))
$name | string | name of the check box list. You can use this name to retrieve the selected value(s) once the form is submitted.
$select | mixed | selection of the check boxes. This can be either a string for single selection or an array for multiple selections.
$data | array | value-label pairs used to generate the check box list. Note, the values will be automatically HTML-encoded, while the labels will not.
$htmlOptions array addtional HTML options. The options will be applied to each checkbox input. The following special options are recognized:
  • template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated check box input tag while "{label}" be replaced by the corresponding check box label.
  • separator: string, specifies the string that separates the generated check boxes.
  • checkAll: string, specifies the label for the "check all" checkbox. If this option is specified, a 'check all' checkbox will be displayed. Clicking on this checkbox will cause all checkboxes checked or unchecked. This option has been available since version 1.0.4.
  • checkAllLast: boolean, specifies whether the 'check all' checkbox should be displayed at the end of the checkbox list. If this option is not set (default) or is false, the 'check all' checkbox will be displayed at the beginning of the checkbox list. This option has been available since version 1.0.4.
  • labelOptions: array, specifies the additional HTML attributes to be rendered for every label tag in the list. This option has been available since version 1.0.10.
{return} | string | the generated check box list

Generates a check box list. A check box list allows multiple selection, like listBox. As a result, the corresponding POST value is an array.

clientChange() method
protected static void clientChange(string $event, array $htmlOptions, boolean $live=true)
$event | string | event name (without 'on')
$htmlOptions array HTML attributes which may contain the following special attributes specifying the client change behaviors:
  • submit: string, specifies the URL that the button should submit to. If empty, the current requested URL will be used.
  • params: array, name-value pairs that should be submitted together with the form. This is only used when 'submit' option is specified.
  • csrf: boolean, whether a CSRF token should be submitted when CHttpRequest::enableCsrfValidation is true. Defaults to false. This option has been available since version 1.0.7. You may want to set this to be true if there is no enclosing form around this element. This option is meaningful only when 'submit' option is set.
  • return: boolean, the return value of the javascript. Defaults to false, meaning that the execution of javascript would not cause the default behavior of the event. This option has been available since version 1.0.2.
  • confirm: string, specifies the message that should show in a pop-up confirmation dialog.
  • ajax: array, specifies the AJAX options (see ajax).
$live | boolean | whether the event should be "live" (a jquery event concept). Defaults to true. This parameter has been available since version 1.1.1.

Generates the JavaScript with the specified client changes.

closeTag() method
public static string closeTag(string $tag)
$tag | string | the tag name
{return} | string | the generated HTML element tag

Generates a close HTML element.

css() method
public static string css(string $text, string $media='')
$text | string | the CSS content
$media | string | the media that this CSS should apply to.
{return} | string | the CSS properly enclosed

Encloses the given CSS content with a CSS tag.

cssFile() method
public static string cssFile(string $url, string $media='')
$url | string | the CSS URL
$media | string | the media that this CSS should apply to.
{return} | string | the CSS link.

Links to the specified CSS file.

dropDownList() method
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
$name | string | the input name
$select | string | the selected value
$data | array | data for generating the list options (value=>display). You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method.
$htmlOptions array additional HTML attributes. Besides normal HTML attributes, a few special attributes are recognized. See clientChange and tag for more details. In addition, the following options are also supported specifically for dropdown list:
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the 'empty' option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
        'value1'=>array('disabled'=>true, 'label'=>'value 1'),
        'value2'=>array('label'=>'value 2'),
    );
    This option has been available since version 1.0.3.
{return} | string | the generated drop down list

Generates a drop down list.

See Also

  • clientChange
  • inputField
  • listData
encode() method
public static string encode(string $text)
$text | string | data to be encoded
{return} | string | the encoded data

Encodes special characters into HTML entities. The application charset will be used for encoding.

See Also

  • http://www.php.net/manual/en/function.htmlspecialchars.php
encodeArray() method (available since v1.0.4)
public static array encodeArray(array $data)
$data | array | data to be encoded
{return} | array | the encoded data

Encodes special characters in an array of strings into HTML entities. Both the array keys and values will be encoded if needed. If a value is an array, this method will also encode it recursively. The application charset will be used for encoding.

See Also

  • http://www.php.net/manual/en/function.htmlspecialchars.php
endForm() method (available since v1.0.4)
public static string endForm()
{return} string the generated tag

Generates a closing form tag.

See Also

  • beginForm
error() method
public static string error(CModel $model, string $attribute, array $htmlOptions=array ( ))
$model | CModel | the data model
$attribute | string | the attribute name
$htmlOptions | array | additional HTML attributes to be rendered in the container div tag. This parameter has been available since version 1.0.7.
{return} | string | the error display. Empty if no errors are found.

Displays the first validation error for a model attribute.

See Also

  • CModel::getErrors
  • errorMessageCss
errorSummary() method
public static string errorSummary(mixed $model, string $header=NULL, string $footer=NULL, array $htmlOptions=array ( ))
$model | mixed | the models whose input errors are to be displayed. This can be either a single model or an array of models.
$header | string | a piece of HTML code that appears in front of the errors
$footer | string | a piece of HTML code that appears at the end of the errors
$htmlOptions | array | additional HTML attributes to be rendered in the container div tag. This parameter has been available since version 1.0.7.
{return} | string | the error summary. Empty if no errors are found.

Displays a summary of validation errors for one or several models.

See Also

  • CModel::getErrors
  • errorSummaryCss
fileField() method
public static string fileField(string $name, string $value='', array $htmlOptions=array ( ))
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated input field

Generates a file input. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'. After the form is submitted, the uploaded file information can be obtained via $_FILES[$name] (see PHP documentation).

See Also

  • inputField
form() method
public static string form(mixed $action='', string $method='post', array $htmlOptions=array ( ))
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.)
$method | string | form method (e.g. post, get)
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated form tag.

Generates an opening form tag. This is a shortcut to beginForm.

getActiveId() method
public static string getActiveId(CModel $model, string $attribute)
$model | CModel | the data model
$attribute | string | the attribute
{return} | string | the element ID for the active field corresponding to the specified model and attribute.

Returns the element ID that is used by methods such as activeTextField. This method has been deprecated since version 1.0.5. Please use activeId instead.

getIdByName() method
public static string getIdByName($name)
$name |  |
{return} | string | the ID generated based on name.

Generates a valid HTML ID based the name.

hiddenField() method
public static string hiddenField(string $name, string $value='', array $htmlOptions=array ( ))
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated input field

Generates a hidden input.

See Also

  • inputField
htmlButton() method (available since v1.0.8)
public static string htmlButton(string $label='button', array $htmlOptions=array ( ))
$label | string | the button label. Note that this value will be directly inserted in the button element without being HTML-encoded.
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates a button using HTML button tag. This method is similar to button except that it generates a 'button' tag instead of 'input' tag.

See Also

  • clientChange
image() method
public static string image(string $src, string $alt='', array $htmlOptions=array ( ))
$src | string | the image URL
$alt | string | the alternative text display
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated image tag

Generates an image tag.

imageButton() method
public static string imageButton(string $src, array $htmlOptions=array ( ))
$src | string | the button label
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates an image submit button.

See Also

  • clientChange
inputField() method
protected static string inputField(string $type, string $name, string $value, array $htmlOptions)
$type | string | the input type (e.g. 'text', 'radio')
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes for the HTML tag (see tag).
{return} | string | the generated input tag

Generates an input HTML tag. This method generates an input HTML tag based on the given input name and value.

label() method
public static string label(string $label, string $for, array $htmlOptions=array ( ))
$label | string | label text. Note, you should HTML-encode the text if needed.
$for | string | the ID of the HTML element that this label is associated with. If this is false, the 'for' attribute for the label tag will not be rendered (since version 1.0.11).
$htmlOptions array additional HTML attributes. Starting from version 1.0.2, the following HTML option is recognized:
  • required: if this is set and is true, the label will be styled with CSS class 'required' (customizable with CHtml::$requiredCss), and be decorated with CHtml::beforeRequiredLabel and CHtml::afterRequiredLabel.
{return} | string | the generated label tag

Generates a label tag.

link() method
public static string link(string $text, mixed $url='#', array $htmlOptions=array ( ))
$text | string | link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag.
$url | mixed | a URL or an action route that can be used to create a URL. See normalizeUrl for more details about how to specify this parameter.
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated hyperlink

Generates a hyperlink tag.

See Also

  • normalizeUrl
  • clientChange
linkButton() method
public static string linkButton(string $label='submit', array $htmlOptions=array ( ))
$label | string | the button label
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates a link submit button.

See Also

  • clientChange
linkTag() method (available since v1.0.1)
public static string linkTag(string $relation=NULL, string $type=NULL, string $href=NULL, string $media=NULL, array $options=array ( ))
$relation | string | rel attribute of the link tag. If null, the attribute will not be generated.
$type | string | type attribute of the link tag. If null, the attribute will not be generated.
$href | string | href attribute of the link tag. If null, the attribute will not be generated.
$media | string | media attribute of the link tag. If null, the attribute will not be generated.
$options | array | other options in name-value pairs
{return} | string | the generated link tag

Generates a link tag that can be inserted in the head section of HTML page. Do not confuse this method with link(). The latter generates a hyperlink.

listBox() method
public static string listBox(string $name, mixed $select, array $data, array $htmlOptions=array ( ))
$name | string | the input name
$select | mixed | the selected value(s). This can be either a string for single selection or an array for multiple selections.
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method.
$htmlOptions array additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized. See clientChange and tag for more details. In addition, the following options are also supported specifically for list box:
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the 'empty' option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
        'value1'=>array('disabled'=>true, 'label'=>'value 1'),
        'value2'=>array('label'=>'value 2'),
    );
    This option has been available since version 1.0.3.
{return} | string | the generated list box

Generates a list box.

See Also

  • clientChange
  • inputField
  • listData
listData() method
public static array listData(array $models, string $valueField, string $textField, string $groupField='')
$models | array | a list of model objects. Starting from version 1.0.3, this parameter can also be an array of associative arrays (e.g. results of CDbCommand::queryAll).
$valueField | string | the attribute name for list option values
$textField | string | the attribute name for list option texts
$groupField | string | the attribute name for list option group names. If empty, no group will be generated.
{return} | array | the list data that can be used in dropDownList and listBox

Generates the data suitable for dropDownList and listBox. Note, this method does not HTML-encode the generated data. You may call encodeArray to encode it if needed. Please refer to the value method on how to specify value field, text field and group field.

listOptions() method
public static string listOptions(mixed $selection, array $listData, array $htmlOptions)
$selection | mixed | the selected value(s). This can be either a string for single selection or an array for multiple selections.
$listData | array | the option data (see listData)
$htmlOptions array additional HTML attributes. The following two special attributes are recognized:
  • encode: boolean, specifies whether to encode the values. Defaults to true. This option has been available since version 1.0.5.
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the 'empty' option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
        'value1'=>array('disabled'=>true, 'label'=>'value 1'),
        'value2'=>array('label'=>'value 2'),
    );
    This option has been available since version 1.0.3.
{return} | string | the generated list options

Generates the list options.

mailto() method (available since v1.0.1)
public static string mailto(string $text, string $email='', array $htmlOptions=array ( ))
$text | string | link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag.
$email | string | email address. If this is empty, the first parameter (link body) will be treated as the email address.
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated mailto link

Generates a mailto link.

See Also

  • clientChange
metaTag() method (available since v1.0.1)
public static string metaTag(string $content, string $name=NULL, string $httpEquiv=NULL, array $options=array ( ))
$content | string | content attribute of the meta tag
$name | string | name attribute of the meta tag. If null, the attribute will not be generated
$httpEquiv | string | http-equiv attribute of the meta tag. If null, the attribute will not be generated
$options | array | other options in name-value pairs (e.g. 'scheme', 'lang')
{return} | string | the generated meta tag

Generates a meta tag that can be inserted in the head section of HTML page.

normalizeUrl() method
public static void normalizeUrl(mixed $url)
$url mixed the parameter to be used to generate a valid URL

Normalizes the input parameter to be a valid URL.

If the input parameter is an empty string, the currently requested URL will be returned.

If the input parameter is a non-empty string, it is treated as a valid URL and will be returned without any change.

If the input parameter is an array, it is treated as a controller route and a list of GET parameters, and the CController::createUrl method will be invoked to create a URL. In this case, the first array element refers to the controller route, and the rest key-value pairs refer to the additional GET parameters for the URL. For example, array('post/list', 'page'=>3) may be used to generate the URL /index.php?r=post/list&page=3.

openTag() method
public static string openTag(string $tag, array $htmlOptions=array ( ))
$tag | string | the tag name
$htmlOptions | array | the element attributes. The values will be HTML-encoded using encode(). Since version 1.0.5, if an 'encode' attribute is given and its value is false, the rest of the attribute values will NOT be HTML-encoded.
{return} | string | the generated HTML element tag

Generates an open HTML element.

pageStateField() method
public static string pageStateField(string $value)
$value | string | the persistent page states in serialized format
{return} | string | the generated hidden field

Generates a hidden field for storing persistent page states. This method is internally used by statefulForm.

passwordField() method
public static string passwordField(string $name, string $value='', array $htmlOptions=array ( ))
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated input field

Generates a password field input.

See Also

  • clientChange
  • inputField
radioButton() method
public static string radioButton(string $name, boolean $checked=false, array $htmlOptions=array ( ))
$name | string | the input name
$checked | boolean | whether the check box is checked
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated radio button

Generates a radio button.

See Also

  • clientChange
  • inputField
radioButtonList() method
public static string radioButtonList(string $name, mixed $select, array $data, array $htmlOptions=array ( ))
$name | string | name of the radio button list. You can use this name to retrieve the selected value(s) once the form is submitted.
$select | mixed | selection of the radio buttons. This can be either a string for single selection or an array for multiple selections.
$data | array | value-label pairs used to generate the radio button list. Note, the values will be automatically HTML-encoded, while the labels will not.
$htmlOptions array addtional HTML options. The options will be applied to each checkbox input. The following special options are recognized:
  • template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated radio button input tag while "{label}" be replaced by the corresponding radio button label.
  • separator: string, specifies the string that separates the generated radio buttons.
  • labelOptions: array, specifies the additional HTML attributes to be rendered for every label tag in the list. This option has been available since version 1.0.10.
{return} | string | the generated radio button list

Generates a radio button list. A radio button list is like a check box list, except that it only allows single selection.

refresh() method (available since v1.1.1)
public static void refresh(integer $seconds, string $url='')
$seconds | integer | the number of seconds to wait before refreshing the page
$url | string | the URL to which the page should be redirected to. If empty, it means the current page.

Registers a 'refresh' meta tag. This method can be invoked anywhere in a view. It will register a 'refresh' meta tag with CClientScript so that the page can be refreshed in the specified seconds.

renderAttributes() method (available since v1.0.5)
protected static string renderAttributes(array $htmlOptions)
$htmlOptions | array | attributes to be rendered
{return} | string | the rendering result

Renders the HTML tag attributes.

resetButton() method
public static string resetButton(string $label='reset', array $htmlOptions=array ( ))
$label | string | the button label
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates a reset button.

See Also

  • clientChange
resolveName() method (available since v1.0.2)
public static string resolveName(CModel $model, string $attribute)
$model | CModel | the data model
$attribute | string | the attribute
{return} | string | the input name

Generates input name for a model attribute. Note, the attribute name may be modified after calling this method if the name contains square brackets (mainly used in tabular input).

resolveNameID() method
public static void resolveNameID(CModel $model, string $attribute, array $htmlOptions)
$model | CModel | the data model
$attribute | string | the attribute
$htmlOptions | array | the HTML options

Generates input name and ID for a model attribute. This method will update the HTML options by setting appropriate 'name' and 'id' attributes. This method may also modify the attribute name if the name contains square brackets (mainly used in tabular input).

script() method
public static string script(string $text)
$text | string | the JavaScript to be enclosed
{return} | string | the enclosed JavaScript

Encloses the given JavaScript within a script tag.

scriptFile() method
public static string scriptFile(string $url)
$url | string | URL for the JavaScript file
{return} | string | the JavaScript file tag

Includes a JavaScript file.

statefulForm() method
public static string statefulForm(mixed $action='', string $method='post', array $htmlOptions=array ( ))
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.)
$method | string | form method (e.g. post, get)
$htmlOptions | array | additional HTML attributes (see tag).
{return} | string | the generated form tag.

Generates a stateful form tag. A stateful form tag is similar to form except that it renders an additional hidden field for storing persistent page states. You should use this method to generate a form tag if you want to access persistent page states when the form is submitted.

submitButton() method
public static string submitButton(string $label='submit', array $htmlOptions=array ( ))
$label | string | the button label
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated button tag

Generates a submit button.

See Also

  • clientChange
tag() method
public static string tag(string $tag, array $htmlOptions=array ( ), mixed $content=false, boolean $closeTag=true)
$tag | string | the tag name
$htmlOptions | array | the element attributes. The values will be HTML-encoded using encode(). Since version 1.0.5, if an 'encode' attribute is given and its value is false, the rest of the attribute values will NOT be HTML-encoded.
$content | mixed | the content to be enclosed between open and close element tags. It will not be HTML-encoded. If false, it means there is no body content.
$closeTag | boolean | whether to generate the close tag.
{return} | string | the generated HTML element tag

Generates an HTML element.

textArea() method
public static string textArea(string $name, string $value='', array $htmlOptions=array ( ))
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated text area

Generates a text area input.

See Also

  • clientChange
  • inputField
textField() method
public static string textField(string $name, string $value='', array $htmlOptions=array ( ))
$name | string | the input name
$value | string | the input value
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)
{return} | string | the generated input field

Generates a text field input.

See Also

  • clientChange
  • inputField
value() method (available since v1.0.5)
public static mixed value(mixed $model, string $attribute, mixed $defaultValue=NULL)
$model | mixed | the model. This can be either an object or an array.
$attribute | string | the attribute name (use dot to concatenate multiple attributes)
$defaultValue | mixed | the default value to return when the attribute does not exist
{return} | mixed | the attribute value

Evaluates the value of the specified attribute for the given model. The attribute name can be given in a dot syntax. For example, if the attribute is "author.firstName", this method will return the value of "$model->author->firstName". A default value (passed as the last parameter) will be returned if the attribute does not exist or is broken in the middle (e.g. $model->author is null). The model can be either an object or an array. If the latter, the attribute is treated as a key of the array. For the example of "author.firstName", if would mean the array value "$model['author']['firstName']".


CJSON

All Packages | Methods
Package | system.web.helpers
Inheritance | class CJSON
Since | 1.0
Version | $Id: CJSON.php 1483 2009-10-27 15:57:33Z qiang.xue $
CJSON converts PHP data to and from JSON format.

Public Methods

Hide inherited methods

Method | Description | Defined By
decode() | decodes a JSON string into appropriate variable | CJSON
encode() | encodes an arbitrary variable into JSON format | CJSON

Protected Methods

Hide inherited methods

Method | Description | Defined By
nameValue() | array-walking function for use in generating JSON-formatted name-value pairs | CJSON
reduceString() | reduce a string by removing leading and trailing comments and whitespace | CJSON
unicodeToUTF8() | This function converts a Unicode array back to its UTF-8 representation | CJSON
utf16beToUTF8() | UTF-8 to UTF-16BE conversion. | CJSON
utf8ToUTF16BE() | UTF-8 to UTF-16BE conversion. | CJSON
utf8ToUnicode() | This function returns any UTF-8 encoded text as a list of | CJSON

Method Details

decode() method
public static mixed decode(string $str, boolean $useArray=true)
$str | string | $str JSON-formatted string
$useArray | boolean | whether to use associative array to represent object data
{return} | mixed | number, boolean, string, array, or object corresponding to given JSON input string. See argument 1 to JSON() above for object-output behavior. Note that decode() always returns strings in ASCII or UTF-8 format!

decodes a JSON string into appropriate variable

encode() method
public static string encode(mixed $var)
$var | mixed | $var any number, boolean, string, array, or object to be encoded. see argument 1 to JSON() above for array-parsing behavior. if var is a strng, note that encode() always expects it to be in ASCII or UTF-8 format!
{return} | string | JSON string representation of input var

encodes an arbitrary variable into JSON format

nameValue() method
protected static string nameValue(string $name, mixed $value)
$name | string | $name name of key to use
$value | mixed | $value reference to an array element to be encoded
{return} | string | JSON-formatted name-value pair, like '"name":value'

array-walking function for use in generating JSON-formatted name-value pairs

reduceString() method
protected static string reduceString($str $str)
$str | $str | string string value to strip of comments and whitespace
{return} | string | string value stripped of comments and whitespace

reduce a string by removing leading and trailing comments and whitespace

unicodeToUTF8() method
protected static void unicodeToUTF8($str)
$str

This function converts a Unicode array back to its UTF-8 representation

See Also

  • utf8ToUnicode()
utf16beToUTF8() method
protected static void utf16beToUTF8($str)
$str

UTF-8 to UTF-16BE conversion.

Maybe really UCS-2 without mb_string due to utf8ToUnicode limits

utf8ToUTF16BE() method
protected static void utf8ToUTF16BE($str, $bom=false)
$str
$bom

UTF-8 to UTF-16BE conversion.

Maybe really UCS-2 without mb_string due to utf8ToUnicode limits

utf8ToUnicode() method
protected static void utf8ToUnicode($str)
$str

This function returns any UTF-8 encoded text as a list of Unicode values:

See Also

  • unicodeToUTF8()


CJavaScript

All Packages | Methods
Package | system.web.helpers
Inheritance | class CJavaScript
Since | 1.0
Version | $Id: CJavaScript.php 1832 2010-02-20 03:22:45Z qiang.xue $
CJavaScript is a helper class containing JavaScript-related handling functions.

Public Methods

Hide inherited methods

Method | Description | Defined By
encode() | Encodes a PHP variable into javascript representation. | CJavaScript
jsonDecode() | Decodes a JSON string. | CJavaScript
jsonEncode() | Returns the JSON representation of the PHP data. | CJavaScript
quote() | Quotes a javascript string. | CJavaScript

Method Details

encode() method
public static string encode(mixed $value)
$value | mixed | PHP variable to be encoded
{return} | string | the encoded string

Encodes a PHP variable into javascript representation.

Example:

$options=array('key1'=>true,'key2'=>123,'key3'=>'value');
echo CJavaScript::encode($options);
// The following javascript code would be generated:
// {'key1':true,'key2':123,'key3':'value'}

For highly complex data structures use jsonEncode and jsonDecode to serialize and unserialize.

jsonDecode() method
public static mixed jsonDecode(string $data, boolean $useArray=true)
$data | string | the data to be decoded
$useArray | boolean | whether to use associative array to represent object data
{return} | mixed | the decoded PHP data

Decodes a JSON string.

jsonEncode() method
public static string jsonEncode(mixed $data)
$data | mixed | the data to be encoded
{return} | string | the JSON representation of the PHP data.

Returns the JSON representation of the PHP data.

quote() method
public static string quote(string $js, boolean $forUrl=false)
$js | string | string to be quoted
$forUrl | boolean | whether this string is used as a URL
{return} | string | the quoted string

Quotes a javascript string. After processing, the string can be safely enclosed within a pair of quotation marks and serve as a javascript string.


CPradoViewRenderer

Package | system.web.renderers
Inheritance | class CPradoViewRenderer » CViewRenderer » CApplicationComponent » CComponent
Implements | IViewRenderer, IApplicationComponent
Since | 1.0
Version | $Id: CPradoViewRenderer.php 1678 2010-01-07 21:02:00Z qiang.xue $
CPradoViewRenderer implements a view renderer that allows users to use a template syntax similar to PRADO templates.

To use CPradoViewRenderer, configure it as an application component named "viewRenderer" in the application configuration:
array(
    'components'=>array(
        ......
        'viewRenderer'=>array(
            'class'=>'CPradoViewRenderer',
        ),
    ),
)

CPradoViewRenderer allows you to write view files with the following syntax:
// PHP tags:
<%= expression %>
// <?php echo expression ?>
<% statement %>
// <?php statement ?>

// component tags:
<com:WigetClass name1="value1" name2='value2' name3={value3} >
// <?php $this->beginWidget('WigetClass',
// array('name1'=>"value1", 'name2'=>'value2', 'name3'=>value3)); ?>
</com:WigetClass >
// <?php $this->endWidget('WigetClass'); ?>
<com:WigetClass name1="value1" name2='value2' name3={value3} />
// <?php $this->widget('WigetClass',
// array('name1'=>"value1", 'name2'=>'value2', 'name3'=>value3)); ?>

// cache tags:
<cache:fragmentID name1="value1" name2='value2' name3={value3} >
// <?php if($this->beginCache('fragmentID',
// array('name1'=>"value1", 'name2'=>'value2', 'name3'=>value3))): ?>
</cache:fragmentID >
// <?php $this->endCache('fragmentID'); endif; ?>

// clip tags:
<clip:clipID >
// <?php $this->beginClip('clipID'); ?>
</clip:clipID >
// <?php $this->endClip('clipID'); ?>

// comment tags:
<!--- comments --->
// the whole tag will be stripped off

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
fileExtension | string | the extension name of the view file. | CViewRenderer
filePermission | integer | the chmod permission for temporary directories and files generated during parsing. | CViewRenderer
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
useRuntimePath | boolean | whether to store the parsing results in the application's runtime directory. | CViewRenderer

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent
renderFile() | Renders a view file. | CViewRenderer

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateViewFile() | Parses the source view file and saves the results as another file. | CPradoViewRenderer
getViewFile() | Generates the resulting view file path. | CViewRenderer

Method Details

generateViewFile() method
protected void generateViewFile(string $sourceFile, string $viewFile)
$sourceFile | string | the source view file path
$viewFile | string | the resulting view file path

Parses the source view file and saves the results as another file. This method is required by the parent class.


CViewRenderer

Package | system.web.renderers
Inheritance | abstract class CViewRenderer » CApplicationComponent » CComponent
Implements | IApplicationComponent, IViewRenderer
Subclasses | CPradoViewRenderer
Since | 1.0
Version | $Id: CViewRenderer.php 1678 2010-01-07 21:02:00Z qiang.xue $
CViewRenderer is the base class for view renderer classes.

A view renderer is an application component that renders views written in a customized syntax.

Once installing a view renderer as a 'viewRenderer' application component, the normal view rendering process will be intercepted by the renderer. The renderer will first parse the source view file and then render the the resulting view file.

Parsing results are saved as temporary files that may be stored under the application runtime directory or together with the source view file.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent
fileExtension | string | the extension name of the view file. | CViewRenderer
filePermission | integer | the chmod permission for temporary directories and files generated during parsing. | CViewRenderer
isInitialized | boolean | whether this application component has been initialized (i. | CApplicationComponent
useRuntimePath | boolean | whether to store the parsing results in the application's runtime directory. | CViewRenderer

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getIsInitialized() |  | CApplicationComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the application component. | CApplicationComponent
raiseEvent() | Raises an event. | CComponent
renderFile() | Renders a view file. | CViewRenderer

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateViewFile() | Parses the source view file and saves the results as another file. | CViewRenderer
getViewFile() | Generates the resulting view file path. | CViewRenderer

Property Details

fileExtension property (available since v1.0.9)
public string $fileExtension;

the extension name of the view file. Defaults to '.php'.

filePermission property
public integer $filePermission;

the chmod permission for temporary directories and files generated during parsing. Defaults to 0755 (owner rwx, group rx and others rx).

useRuntimePath property
public boolean $useRuntimePath;

whether to store the parsing results in the application's runtime directory. Defaults to true. If false, the parsing results will be saved as files under the same directory as the source view files and the file names will be the source file names appended with letter 'c'.

Method Details

generateViewFile() method
abstract protected void generateViewFile(string $sourceFile, string $viewFile)
$sourceFile | string | the source view file path
$viewFile | string | the resulting view file path

Parses the source view file and saves the results as another file.

getViewFile() method
protected string getViewFile(string $file)
$file | string | source view file path
{return} | string | resulting view file path

Generates the resulting view file path.

renderFile() method
public mixed renderFile(CBaseController $context, string $sourceFile, mixed $data, boolean $return)
$context | CBaseController | the controller or widget who is rendering the view file.
$sourceFile | string | the view file path
$data | mixed | the data to be passed to the view
$return | boolean | whether the rendering result should be returned
{return} | mixed | the rendering result, or null if the rendering result is not needed.

Renders a view file. This method is required by IViewRenderer.


CSoapObjectWrapper

Package | system.web.services
Inheritance | class CSoapObjectWrapper
Since | 1.0.5
Version | $Id: CWebService.php 1678 2010-01-07 21:02:00Z qiang.xue $
CSoapObjectWrapper is a wrapper class internally used when SoapServer::setObject() is not defined.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
object | object | the service provider | CSoapObjectWrapper

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | PHP __call magic method. | CSoapObjectWrapper
__construct() | Constructor. | CSoapObjectWrapper

Property Details

object property
public object $object;

the service provider

Method Details

__call() method
public mixed __call(string $name, array $arguments)
$name | string | method name
$arguments | array | method arguments
{return} | mixed | method return value

PHP __call magic method. This method calls the service provider to execute the actual logic.

__construct() method
public void __construct(object $object)
$object object the service provider

Constructor.


CWebService

Package | system.web.services
Inheritance | class CWebService » CComponent
Since | 1.0
Version | $Id: CWebService.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWebService encapsulates SoapServer and provides a WSDL-based web service.

PHP SOAP extension is required.

CWebService makes use of CWsdlGenerator and can generate the WSDL on-the-fly without requiring you to write complex WSDL.

To generate the WSDL based on doc comment blocks in the service provider class, call generateWsdl or renderWsdl. To process the web service requests, call run.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actor | string | actor of the SOAP service. | CWebService
cacheID | string | the ID of the cache application component that is used to cache the generated WSDL. | CWebService
classMap | array | a list of classes that are declared as complex types in WSDL. | CWebService
encoding | string | encoding of the Web service. | CWebService
methodName | string | the currently requested method name. | CWebService
persistence | integer | the persistence mode of the SOAP server. | CWebService
provider | string|object | the web service provider class or object. | CWebService
serviceUrl | string | the URL for the Web service. | CWebService
soapVersion | string | SOAP version (e. | CWebService
wsdlCacheDuration | integer | number of seconds that the generated WSDL can remain valid in cache. | CWebService
wsdlUrl | string | the URL for WSDL. | CWebService

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
options | array | options for creating SoapServer instance | CWebService

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWebService
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
generateWsdl() | Generates the WSDL as defined by the provider. | CWebService
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getMethodName() |  | CWebService
handleError() | The PHP error handler. | CWebService
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
renderWsdl() | Generates and displays the WSDL as defined by the provider. | CWebService
run() | Handles the web service request. | CWebService

Protected Methods

Hide inherited methods

Method | Description | Defined By
getOptions() |  | CWebService

Property Details

actor property
public string $actor;

actor of the SOAP service. Defaults to null, meaning not set.

cacheID property (available since v1.0.10)
public string $cacheID;

the ID of the cache application component that is used to cache the generated WSDL. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching WSDL.

classMap property
public array $classMap;

a list of classes that are declared as complex types in WSDL. This should be an array with WSDL types as keys and names of PHP classes as values. A PHP class can also be specified as a path alias.

See Also

  • http://www.php.net/manual/en/function.soap-soapserver-construct.php
encoding property
public string $encoding;

encoding of the Web service. Defaults to 'UTF-8'.

methodName property read-only
public string getMethodName()

the currently requested method name. Empty if no method is being requested.

options property read-only
protected array getOptions()

options for creating SoapServer instance

See Also

  • http://www.php.net/manual/en/function.soap-soapserver-construct.php
persistence property
public integer $persistence;

the persistence mode of the SOAP server.

See Also

  • http://www.php.net/manual/en/function.soap-soapserver-setpersistence.php
provider property
public string|object $provider;

the web service provider class or object. If specified as a class name, it can be a path alias.

serviceUrl property
public string $serviceUrl;

the URL for the Web service. This is required by generateWsdl() and renderWsdl().

soapVersion property
public string $soapVersion;

SOAP version (e.g. '1.1' or '1.2'). Defaults to null, meaning not set.

wsdlCacheDuration property
public integer $wsdlCacheDuration;

number of seconds that the generated WSDL can remain valid in cache. Defaults to 0, meaning no caching.

wsdlUrl property
public string $wsdlUrl;

the URL for WSDL. This is required by run().

Method Details

__construct() method
public void __construct(mixed $provider, string $wsdlUrl, string $serviceUrl)
$provider | mixed | the web service provider class name or object
$wsdlUrl | string | the URL for WSDL. This is required by run().
$serviceUrl | string | the URL for the Web service. This is required by generateWsdl() and renderWsdl().

Constructor.

generateWsdl() method
public string generateWsdl()
{return} string the generated WSDL

Generates the WSDL as defined by the provider. The cached version may be used if the WSDL is found valid in cache.

See Also

  • wsdlCacheDuration
getMethodName() method
public string getMethodName()
{return} string the currently requested method name. Empty if no method is being requested.

getOptions() method
protected array getOptions()
{return} array options for creating SoapServer instance

See Also

  • http://www.php.net/manual/en/function.soap-soapserver-construct.php
handleError() method
public void handleError(CErrorEvent $event)
$event CErrorEvent the PHP error event

The PHP error handler.

renderWsdl() method
public void renderWsdl()

Generates and displays the WSDL as defined by the provider.

See Also

  • generateWsdl
run() method
public void run()

Handles the web service request.


CWebServiceAction

Package | system.web.services
Inheritance | class CWebServiceAction » CAction » CComponent
Implements | IAction
Since | 1.0
Version | $Id: CWebServiceAction.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWebServiceAction implements an action that provides Web services.

CWebServiceAction serves for two purposes. On the one hand, it displays the WSDL content specifying the Web service APIs. On the other hand, it invokes the requested Web service API. A GET parameter named ws is used to differentiate these two aspects: the existence of the GET parameter indicates performing the latter action.

By default, CWebServiceAction will use the current controller as the Web service provider. See CWsdlGenerator on how to declare methods that can be remotely invoked.

Note, PHP SOAP extension is required for this action.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
classMap | array | a list of PHP classes that are declared as complex types in WSDL. | CWebServiceAction
controller | CController | the controller who owns this action. | CAction
id | string | id of this action | CAction
provider | mixed | the Web service provider object or class name. | CWebServiceAction
service | CWebService | Returns the Web service instance currently being used. | CWebServiceAction
serviceOptions | array | the initial property values for the CWebService object. | CWebServiceAction
serviceUrl | string | the URL for the Web service. | CWebServiceAction
serviceVar | string | the name of the GET parameter that differentiates a WSDL request from a Web service request. | CWebServiceAction
wsdlUrl | string | the URL for WSDL. | CWebServiceAction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CAction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CAction
getService() | Returns the Web service instance currently being used. | CWebServiceAction
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
run() | Runs the action. | CWebServiceAction

Protected Methods

Hide inherited methods

Method | Description | Defined By
createWebService() | Creates a CWebService instance. | CWebServiceAction

Property Details

classMap property
public array $classMap;

a list of PHP classes that are declared as complex types in WSDL. This should be an array with WSDL types as keys and names of PHP classes as values. A PHP class can also be specified as a path alias.

See Also

  • http://www.php.net/manual/en/soapclient.soapclient.php
provider property
public mixed $provider;

the Web service provider object or class name. If specified as a class name, it can be a path alias. Defaults to null, meaning the current controller is used as the service provider. If the provider implements the interface IWebServiceProvider, it will be able to intercept the remote method invocation and perform additional tasks (e.g. authentication, logging).

service property read-only
public CWebService getService()

Returns the Web service instance currently being used.

serviceOptions property
public array $serviceOptions;

the initial property values for the CWebService object. The array keys are property names of CWebService and the array values are the corresponding property initial values.

serviceUrl property
public string $serviceUrl;

the URL for the Web service. Defaults to null, meaning the URL for this action is used to provide Web services. In this case, a GET parameter named serviceVar will be used to deteremine whether the current request is for WSDL or Web service.

serviceVar property
public string $serviceVar;

the name of the GET parameter that differentiates a WSDL request from a Web service request. If this GET parameter exists, the request is considered as a Web service request; otherwise, it is a WSDL request. Defaults to 'ws'.

wsdlUrl property
public string $wsdlUrl;

the URL for WSDL. Defaults to null, meaning the URL for this action is used to serve WSDL document.

Method Details

createWebService() method
protected CWebService createWebService(mixed $provider, string $wsdlUrl, string $serviceUrl)
$provider | mixed | the web service provider class name or object
$wsdlUrl | string | the URL for WSDL.
$serviceUrl | string | the URL for the Web service.
{return} | CWebService | the Web service instance

Creates a CWebService instance. You may override this method to customize the created instance.

getService() method
public CWebService getService()
{return} CWebService the Web service instance

Returns the Web service instance currently being used.

run() method
public void run()

Runs the action. If the GET parameter serviceVar exists, the action handle the remote method invocation. If not, the action will serve WSDL content;


CWsdlGenerator

All Packages | Methods
Package | system.web.services
Inheritance | class CWsdlGenerator » CComponent
Since | 1.0
Version | $Id: CWsdlGenerator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWsdlGenerator generates the WSDL for a given service class.

The WSDL generation is based on the doc comments found in the service class file. In particular, it recognizes the '@soap' tag in the comment and extracts API method and type definitions.

In a service class, a remote invokable method must be a public method with a doc comment block containing the '@soap' tag. In the doc comment, the type and name of every input parameter and the type of the return value should be declared using the standard phpdoc format.

CWsdlGenerator recognizes the following primitive types (case-sensitive) in the parameter and return type declarations:
  • str/string: maps to xsd:string;
  • int/integer: maps to xsd:int;
  • float/double: maps to xsd:float;
  • bool/boolean: maps to xsd:boolean;
  • date: maps to xsd:date;
  • time: maps to xsd:time;
  • datetime: maps to xsd:dateTime;
  • array: maps to xsd:string;
  • object: maps to xsd:struct;
  • mixed: maps to xsd:anyType.

If a type is not a primitive type, it is considered as a class type, and CWsdlGenerator will look for its property declarations. Only public properties are considered, and they each must be associated with a doc comment block containg the '@soap' tag. The doc comment block should declare the type of the property.

CWsdlGenerator recognizes the array type with the following format:
typeName[]: maps to tns:typeNameArray

The following is an example declaring a remote invokable method:
/ **
  * A foo method.
  * @param string name of something
  * @param string value of something
  * @return string[] some array
  * @soap
  * /
public function foo($name,$value) {...}

And the following is an example declaring a class with remote accessible properties:
class Foo {
    / **
      * @var string name of foo
      * @soap
      * /
    public $name;
    / **
      * @var Member[] members of foo
      * @soap
      * /
    public $members;
}
In the above, the 'members' property is an array of 'Member' objects. Since 'Member' is not a primitive type, CWsdlGenerator will look further to find the definition of 'Member'.

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
generateWsdl() | Generates the WSDL for the given class. | CWsdlGenerator
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent

Method Details

generateWsdl() method
public string generateWsdl(string $className, string $serviceUrl, string $encoding='UTF-8')
$className | string | class name
$serviceUrl | string | Web service URL
$encoding | string | encoding of the WSDL. Defaults to 'UTF-8'.
{return} | string | the generated WSDL

Generates the WSDL for the given class.


CActiveForm

Package | system.web.widgets
Inheritance | class CActiveForm » CWidget » CBaseController » CComponent
Since | 1.1.1
Version | $Id: CActiveForm.php 1803 2010-02-16 12:54:00Z qiang.xue $
CActiveForm provides a set of methods that can facilitate creating a form associated with some data models.

CActiveForm implements a set of wrapper methods that call the corresponding 'active' methods in CHtml. For example, the textField method is a wrapper of CHtml::activeTextField.

The 'beginWidget' and 'endWidget' call of CActiveForm widget will render the open and close form tags. Anything in between are rendered as form content (such as input fields, labels). We can call the wrapper methods of CActiveForm to generate these form contents. For example, calling CActiveFinder::textField, which is a wrapper of CHtml::activeTextField, would generate an input field for a specified model attribute.

Besides the wrapper methods, CActiveForm also implements an important feature known as AJAX validation. This feature may be turned on setting enableAjaxValidation to be true. When the user enters some value in an input field, the AJAX validation feature would trigger an AJAX request to the server to call for validating the model with the current user inputs. If there are any validation errors, the corresponding error messages will show up next to the input fields immediately.

The AJAX validation feature may greatly improve the user experience at entering data into a form. Because the validation is done on the server side using the rules defined in the data model, no extra javascript code needs to be written. More importantly, and the validation result is consistent with the server-side validation. And in case when the user turns off javascript in his browser, it automatically falls back to traditional validation via whole page submission.

To use CActiveForm with AJAX validation, one needs to write both the view code and the controller action code.

The following is a piece of sample view code:
<?php $form = $this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'enableAjaxValidation'=>true,
)); ?>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'firstName'); ?>
    <?php echo $form->textField($model,'firstName'); ?>
    <?php echo $form->error($model,'firstName'); ?>
</div>
<div class="row">
    <?php echo $form->labelEx($model,'lastName'); ?>
    <?php echo $form->textField($model,'lastName'); ?>
    <?php echo $form->error($model,'lastName'); ?>
</div>

<?php $this->endWidget(); ?>

To respond to the AJAX validation requests, we need the following class code:
public function actionCreate()
{
    $model=new User;
    $this->performAjaxValidation($model);
    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        if($model->save())
            $this->redirect('index');
    }
    $this->render('create',array('model'=>$model));
}

protected function performAjaxValidation($model)
{
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
}
The method performAjaxValidation is the main extra code we add to our traditional model creation action code. In this method, we check if the request is submitted via AJAX by the 'user-form'. If so, we validate the model and return the validation results. We may call the same method in model update action.

On the client side, an input field may be in one of the four states: initial (not validated), validating, error and success. To differentiate these states, CActiveForm automatically assigns different CSS classes for the last three states to the HTML element containing the input field. By default, these CSS classes are named as 'validating', 'error' and 'success', respectively. They may be changed by configuring the options property or specifying in the error method.

Sometimes, we may want to limit the AJAX validation to certain model attributes only. This can be achieved by setting the model with a scenario that is specific for AJAX validation. Then only list those attributes that need AJAX validation in the scenario in CModel::rules() declaration.

There are some limitations of CActiveForm regarding to its AJAX validation support. First, it does not validate with file upload fields. Second, it should not be used to perform validations that may cause server-side state change. For example, it is not suitable to perform CAPTCHA validation done by CCaptchAction because each validation request will increase the number of tests by one. Third, it is not designed to work with tabular data input for the moment.

Because CActiveForm relies on submitting the whole form in AJAX mode to perform the validation, if the form has a lot of data to submit, the performance may not be good. In this case, you should design your own lightweight AJAX validation.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
action | mixed | the form action URL (see normalizeUrl for details about this parameter. | CActiveForm
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
clientOptions | array | the options to be passed to the javascript validation plugin. | CActiveForm
controller | CController | the controller that this widget belongs to. | CWidget
enableAjaxValidation | boolean | whether to enable data validation via AJAX. | CActiveForm
errorMessageCssClass | string | the CSS class name for error messages. | CActiveForm
htmlOptions | array | additional HTML attributes that should be rendered for the form tag. | CActiveForm
id | string | id of the widget. | CWidget
method | string | the form submission method. | CActiveForm
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
stateful | boolean | whether to generate a stateful form (See CHtml::statefulForm). | CActiveForm
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
checkBox() | Renders a checkbox for a model attribute. | CActiveForm
checkBoxList() | Renders a checkbox list for a model attribute. | CActiveForm
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
dropDownList() | Renders a dropdown list for a model attribute. | CActiveForm
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
error() | Displays the first validation error for a model attribute. | CActiveForm
errorSummary() | Displays a summary of validation errors for one or several models. | CActiveForm
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
fileField() | Renders a file field for a model attribute. | CActiveForm
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
hiddenField() | Renders a hidden field for a model attribute. | CActiveForm
init() | Initializes the widget. | CActiveForm
label() | Renders an HTML label for a model attribute. | CActiveForm
labelEx() | Renders an HTML label for a model attribute. | CActiveForm
listBox() | Renders a list box for a model attribute. | CActiveForm
passwordField() | Renders a password field for a model attribute. | CActiveForm
radioButton() | Renders a radio button for a model attribute. | CActiveForm
radioButtonList() | Renders a radio button list for a model attribute. | CActiveForm
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Runs the widget. | CActiveForm
setId() |  | CWidget
textArea() | Renders a text area for a model attribute. | CActiveForm
textField() | Renders a text field for a model attribute. | CActiveForm
validate() | Validates one or several models and returns the results in JSON format. | CActiveForm
widget() | Creates a widget and executes it. | CBaseController

Property Details

action property
public mixed $action;

the form action URL (see normalizeUrl for details about this parameter.) If not set, the current page URL is used.

clientOptions property
public array $clientOptions;

the options to be passed to the javascript validation plugin. The following options are supported:

  • ajaxVar: string, the name of the parameter indicating the request is an AJAX request. When the AJAX validation is triggered, a parameter named as this property will be sent together with the other form data to the server. The parameter value is the form ID. The server side can then detect who triggers the AJAX validation and react accordingly. Defaults to 'ajax'.
  • validationUrl: string, the URL that performs the AJAX validations. If not set, it will take the value of action.
  • validationDelay: integer, the number of milliseconds that an AJAX validation should be delayed after an input is changed. A value 0 means the validation will be triggered immediately when an input is changed. A value greater than 0 means changing several inputs may only trigger a single validation if they happen fast enough, which may help reduce the server load. Defaults to 100 (0.1 second).
  • validateOnSubmit: boolean, whether to perform AJAX validation when the form is being submitted. If there are any validation errors, the form submission will be stopped. Defaults to false.
  • validateOnChange: boolean, whether to trigger an AJAX validation each time when an input's value is changed. You may want to turn this off if it causes too much performance impact, because each AJAX validation request will submit the data of the whole form. Defaults to true.
  • validateOnType: boolean, whether to trigger an AJAX validation each time when the user presses a key. When setting this property to be true, you should tune up the 'validationDelay' option to avoid triggering too many AJAX validations. Defaults to false.
  • hideErrorMessage: boolean, whether to hide the error message even if there is an error. Defaults to false, which means the error message will show up whenever the input has an error.
  • inputContainer: string, the jQuery selector for the HTML element containing the input field. During the validation process, CActiveForm will set different CSS class for the container element to indicate the state change. If not set, it means the closest 'div' element that contains the input field.
  • errorCssClass: string, the CSS class to be assigned to the container whose associated input has AJAX validation error. Defaults to 'error'.
  • successCssClass: string, the CSS class to be assigned to the container whose associated input passes AJAX validation without any error. Defaults to 'success'.
  • validatingCssClass: string, the CSS class to be assigned to the container whose associated input is currently being validated via AJAX. Defaults to 'validating'.
  • errorMessageCssClass: string, the CSS class assigned to the error messages returned by AJAX validations. Defaults to 'errorMessage'.

Some of the above options may be overridden in individual calls of error(). They include: validationDelay, validateOnChange, validateOnType, hideErrorMessage, inputContainer, errorCssClass, successCssClass, and validatingCssClass.

enableAjaxValidation property
public boolean $enableAjaxValidation;

whether to enable data validation via AJAX. Defaults to false. When this property is set true, you should

errorMessageCssClass property
public string $errorMessageCssClass;

the CSS class name for error messages. Defaults to 'errorMessage'. Individual error call may override this value by specifying the 'class' HTML option.

htmlOptions property
public array $htmlOptions;

additional HTML attributes that should be rendered for the form tag.

method property
public string $method;

the form submission method. This should be either 'post' or 'get'. Defaults to 'post'.

stateful property
public boolean $stateful;

whether to generate a stateful form (See CHtml::statefulForm). Defaults to false.

Method Details

checkBox() method
public void checkBox($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a checkbox for a model attribute. This method is a wrapper of CHtml::activeCheckBox. Please check CHtml::activeCheckBox for detailed information about the parameters for this method.

checkBoxList() method
public void checkBoxList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a checkbox list for a model attribute. This method is a wrapper of CHtml::activeCheckBoxList. Please check CHtml::activeCheckBoxList for detailed information about the parameters for this method.

dropDownList() method
public void dropDownList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a dropdown list for a model attribute. This method is a wrapper of CHtml::activeDropDownList. Please check CHtml::activeDropDownList for detailed information about the parameters for this method.

error() method
public string error(CModel $model, string $attribute, array $htmlOptions=array ( ), boolean $enableAjaxValidation=true)
$model | CModel | the data model
$attribute | string | the attribute name
$htmlOptions array additional HTML attributes to be rendered in the container div tag. Besides all those options available in CHtml::error, the following options are recognized in addition:
  • validationDelay
  • validateOnChange
  • validateOnType
  • hideErrorMessage
  • inputContainer
  • errorCssClass
  • successCssClass
  • validatingCssClass
These options override the corresponding options as declared in options for this particular model attribute. For more details about these options, please refer to clientOptions. Note that these options are only used when enableAjaxValidation is set true.
$enableAjaxValidation | boolean | whether to enable AJAX validation for the specified attribute. Note that in order toe enable AJAX validation, both enableAjaxValidation and this parameter must be true.
{return} | string | the validation result (error display or success message).

Displays the first validation error for a model attribute. This is similar to CHtml::error except that it registers the model attribute so that if its value is changed by users, an AJAX validation may be triggered.

See Also

  • CHtml::error
errorSummary() method
public string errorSummary(mixed $models, string $header=NULL, string $footer=NULL, array $htmlOptions=array ( ))
$models | mixed | the models whose input errors are to be displayed. This can be either a single model or an array of models.
$header | string | a piece of HTML code that appears in front of the errors
$footer | string | a piece of HTML code that appears at the end of the errors
$htmlOptions | array | additional HTML attributes to be rendered in the container div tag.
{return} | string | the error summary. Empty if no errors are found.

Displays a summary of validation errors for one or several models. This method is very similar to CHtml::errorSummary except that it also works when AJAX validation is performed.

See Also

  • CHtml::errorSummary
fileField() method
public void fileField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a file field for a model attribute. This method is a wrapper of CHtml::activeFileField. Please check CHtml::activeFileField for detailed information about the parameters for this method.

hiddenField() method
public void hiddenField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a hidden field for a model attribute. This method is a wrapper of CHtml::activeHiddenField. Please check CHtml::activeHiddenField for detailed information about the parameters for this method.

init() method
public void init()

Initializes the widget. This renders the form open tag.

label() method
public void label($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders an HTML label for a model attribute. This method is a wrapper of CHtml::activeLabel. Please check CHtml::activeLabel for detailed information about the parameters for this method.

labelEx() method
public void labelEx($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders an HTML label for a model attribute. This method is a wrapper of CHtml::activeLabelEx. Please check CHtml::activeLabelEx for detailed information about the parameters for this method.

listBox() method
public void listBox($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a list box for a model attribute. This method is a wrapper of CHtml::activeListBox. Please check CHtml::activeListBox for detailed information about the parameters for this method.

passwordField() method
public void passwordField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a password field for a model attribute. This method is a wrapper of CHtml::activePasswordField. Please check CHtml::activePasswordField for detailed information about the parameters for this method.

radioButton() method
public void radioButton($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a radio button for a model attribute. This method is a wrapper of CHtml::activeRadioButton. Please check CHtml::activeRadioButton for detailed information about the parameters for this method.

radioButtonList() method
public void radioButtonList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a radio button list for a model attribute. This method is a wrapper of CHtml::activeRadioButtonList. Please check CHtml::activeRadioButtonList for detailed information about the parameters for this method.

run() method
public void run()

Runs the widget. This registers the necessary javascript code and renders the form close tag.

textArea() method
public void textArea($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a text area for a model attribute. This method is a wrapper of CHtml::activeTextArea. Please check CHtml::activeTextArea for detailed information about the parameters for this method.

textField() method
public void textField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a text field for a model attribute. This method is a wrapper of CHtml::activeTextField. Please check CHtml::activeTextField for detailed information about the parameters for this method.

validate() method
public static string validate(mixed $models, array $attributes=NULL, boolean $loadInput=true)
$models | mixed | a single model instance or an array of models.
$attributes | array | list of attributes that should be validated. Defaults to null, meaning any attribute listed in the applicable validation rules of the models should be validated. If this parameter is given as a list of attributes, only the listed attributes will be validated.
$loadInput | boolean | whether to load the data from $_POST array in this method. If this is true, the model will be populated from $_POST[ModelClass].
{return} | string | the JSON representation of the validation error messages.

Validates one or several models and returns the results in JSON format. This is a helper method that simplies the way of writing AJAX validation code.


CAutoComplete

Package | system.web.widgets
Inheritance | class CAutoComplete » CInputWidget » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CAutoComplete.php 1678 2010-01-07 21:02:00Z qiang.xue $
CAutoComplete generates an auto-complete text field.

CAutoComplete is based on the jQuery Autocomplete.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CInputWidget
autoFill | boolean | fill the textinput while still selecting a value, replacing the value if more is typed or something else is selected. | CAutoComplete
cacheLength | integer | the number of backend query results to store in cache. | CAutoComplete
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CAutoComplete
data | array | data that would be saved as client-side data to provide candidate selections. | CAutoComplete
delay | integer | the delay in milliseconds the autocompleter waits after a keystroke to activate itself. | CAutoComplete
extraParams | array | extra parameters for the backend. | CAutoComplete
formatItem | string | a javascript function that provides advanced markup for an item. | CAutoComplete
formatMatch | string | a javascript function that can be used to limit the data that autocomplete searches for matches. | CAutoComplete
formatResult | string | a javascript function that provides the formatting for the value to be put into the input field. | CAutoComplete
highlight | boolean|string | Whether and how to highlight matches in the select box. | CAutoComplete
htmlOptions | array | additional HTML options to be rendered in the input tag | CInputWidget
id | string | id of the widget. | CWidget
inputClass | string | the CSS class for the input element. | CAutoComplete
loadingClass | string | the CSS class used when the data is being loaded from backend. | CAutoComplete
matchCase | boolean | whether or not the comparison is case sensitive. | CAutoComplete
matchContains | boolean | whether or not the comparison looks inside (i. | CAutoComplete
matchSubset | boolean | whether or not the autocompleter can use a cache for more specific queries. | CAutoComplete
max | integer | limit the number of items in the select box. | CAutoComplete
methodChain | string | the chain of method calls that would be appended at the end of the autocomplete constructor. | CAutoComplete
minChars | integer | the minimum number of characters a user has to type before the autocompleter activates. | CAutoComplete
model | CModel | the data model associated with this widget. | CInputWidget
multiple | boolean | whether to allow more than one autocompleted-value to enter. | CAutoComplete
multipleSeparator | string | seperator to put between values when using multiple option. | CAutoComplete
mustMatch | boolean | if set to true, the autocompleter will only allow results that are presented by the backend. | CAutoComplete
name | string | the input name. | CInputWidget
options | array | additional options that can be passed to the constructor of the autocomplete js object. | CAutoComplete
owner | CBaseController | owner/creator of this widget. | CWidget
resultsClass | string | the CSS class for the dropdown list. | CAutoComplete
scroll | boolean | whether to scroll when more results than configured via scrollHeight are available. | CAutoComplete
scrollHeight | integer | height of scrolled autocomplete control in pixels. | CAutoComplete
selectFirst | boolean | if this is set to true, the first autocomplete value will be automatically selected on tab/return, even if it has not been handpicked by keyboard or mouse action. | CAutoComplete
skin | mixed | the name of the skin to be used by this widget. | CWidget
textArea | boolean | whether to show the autocomplete using a text area. | CAutoComplete
url | string|array | the URL that can return the candidate selections. | CAutoComplete
value | string | the input value | CInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget
width | integer | specify a custom width for the select box. | CAutoComplete

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
clientOptions | array | the javascript options | CAutoComplete

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CAutoComplete
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CAutoComplete
registerCssFile() | Registers the needed CSS file. | CAutoComplete
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
getClientOptions() |  | CAutoComplete
hasModel() |  | CInputWidget
resolveNameID() |  | CInputWidget

Property Details

autoFill property
public boolean $autoFill;

fill the textinput while still selecting a value, replacing the value if more is typed or something else is selected. Defaults to false.

cacheLength property
public integer $cacheLength;

the number of backend query results to store in cache. If set to 1 (the current result), no caching will happen. Must be >= 1. Defaults to 10.

clientOptions property read-only
protected array getClientOptions()

the javascript options

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

data property
public array $data;

data that would be saved as client-side data to provide candidate selections. Each array element can be string or an associative array. The url property will be ignored if this property is set.

See Also

  • url
delay property
public integer $delay;

the delay in milliseconds the autocompleter waits after a keystroke to activate itself. Defaults to 400.

extraParams property
public array $extraParams;

extra parameters for the backend. If you were to specify array('bar'=>4), the autocompleter would call the backend with a GET parameter 'bar' 4. The param can be a function that is called to calculate the param before each request.

formatItem property
public string $formatItem;

a javascript function that provides advanced markup for an item. For each row of results, this function will be called. The returned value will be displayed inside an LI element in the results list. Autocompleter will provide 4 parameters: the results row, the position of the row in the list of results (starting at 1), the number of items in the list of results and the search term. The default behavior assumes that a single row contains a single value.

formatMatch property
public string $formatMatch;

a javascript function that can be used to limit the data that autocomplete searches for matches. For example, there may be items you want displayed to the user, but don't want included in the data that's searched. The function is called with the same arguments as formatItem. Defaults to formatItem.

formatResult property
public string $formatResult;

a javascript function that provides the formatting for the value to be put into the input field. Again three arguments: Data, position (starting with one) and total number of data. The default behavior assumes either plain data to use as result or uses the same value as provided by formatItem.

highlight property
public boolean|string $highlight;

Whether and how to highlight matches in the select box. Set to false to disable. Set to a javascript function to customize. The function gets the value as the first argument and the search term as the second and must return the formatted value. Defaults to Wraps the search term in a <strong> element.

inputClass property
public string $inputClass;

the CSS class for the input element. Defaults to "ac_input".

loadingClass property
public string $loadingClass;

the CSS class used when the data is being loaded from backend. Defaults to "ac_loading".

matchCase property
public boolean $matchCase;

whether or not the comparison is case sensitive. Important only if you use caching. Defaults to false.

matchContains property
public boolean $matchContains;

whether or not the comparison looks inside (i.e. does "ba" match "foo bar") the search results. Important only if you use caching. Don't mix with autofill. Defaults to false.

matchSubset property
public boolean $matchSubset;

whether or not the autocompleter can use a cache for more specific queries. This means that all matches of "foot" are a subset of all matches for "foo". Usually this is true, and using this options decreases server load and increases performance. Only useful with cacheLength settings bigger than one, like 10. Defaults to true.

max property
public integer $max;

limit the number of items in the select box. Is also sent as a "limit" parameter with a remote request. Defaults to 10.

methodChain property
public string $methodChain;

the chain of method calls that would be appended at the end of the autocomplete constructor. For example, ".result(function(...){})" would cause the specified js function to execute when the user selects an option.

minChars property
public integer $minChars;

the minimum number of characters a user has to type before the autocompleter activates. Defaults to 1.

multiple property
public boolean $multiple;

whether to allow more than one autocompleted-value to enter. Defaults to false.

multipleSeparator property
public string $multipleSeparator;

seperator to put between values when using multiple option. Defaults to ", ".

mustMatch property
public boolean $mustMatch;

if set to true, the autocompleter will only allow results that are presented by the backend. Note that illegal values result in an empty input box. Defaults to false.

options property
public array $options;

additional options that can be passed to the constructor of the autocomplete js object. This allows you to override existing functions of the autocomplete js class (e.g. the parse() function)

If you want to provide JavaScript native code, you have to prefix the string with js: otherwise it will be enclosed by quotes.

resultsClass property
public string $resultsClass;

the CSS class for the dropdown list. Defaults to "ac_results".

scroll property
public boolean $scroll;

whether to scroll when more results than configured via scrollHeight are available. Defaults to true.

scrollHeight property
public integer $scrollHeight;

height of scrolled autocomplete control in pixels. Defaults to 180.

selectFirst property
public boolean $selectFirst;

if this is set to true, the first autocomplete value will be automatically selected on tab/return, even if it has not been handpicked by keyboard or mouse action. If there is a handpicked (highlighted) result, that result will take precedence. Defaults to true.

textArea property (available since v1.0.4)
public boolean $textArea;

whether to show the autocomplete using a text area. Defaults to false, meaning a text field is used.

url property
public string|array $url;

the URL that can return the candidate selections. A 'q' GET parameter will be sent with the URL which contains what the user has entered so far. If the URL is given as an array, it is considered as a route to a controller action and will be used to generate a URL using CController::createUrl; If the URL is an empty string, the currently requested URL is used. This property will be ignored if data is set.

See Also

  • data
width property
public integer $width;

specify a custom width for the select box. Defaults to the width of the input element.

Method Details

getClientOptions() method
protected array getClientOptions()
{return} array the javascript options

init() method
public void init()

Initializes the widget. This method registers all needed client scripts and renders the autocomplete input.

registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.


CClipWidget

Package | system.web.widgets
Inheritance | class CClipWidget » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CClipWidget.php 1678 2010-01-07 21:02:00Z qiang.xue $
CClipWidget records its content and makes it available elsewhere.

Content rendered between its init() and run() calls are saved as a clip in the controller. The clip is named after the widget ID.

See CBaseController::beginClip and CBaseController::endClip for a shortcut usage of CClipWidget.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
owner | CBaseController | owner/creator of this widget. | CWidget
renderClip | boolean | whether to render the clip content in place. | CClipWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Starts recording a clip. | CClipWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Ends recording a clip. | CClipWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

renderClip property
public boolean $renderClip;

whether to render the clip content in place. Defaults to false, meaning the captured clip will not be displayed.

Method Details

init() method
public void init()

Starts recording a clip.

run() method
public void run()

Ends recording a clip. This method stops output buffering and saves the rendering result as a named clip in the controller.


CContentDecorator

All Packages | Properties | Methods | Events
Package | system.web.widgets
Inheritance | class CContentDecorator » COutputProcessor » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CContentDecorator.php 1678 2010-01-07 21:02:00Z qiang.xue $
CContentDecorator decorates the content it encloses with the specified view.

CContentDecorator is mostly used to implement nested layouts, i.e., a layout is embedded within another layout. CBaseController defines a pair of convenient methods to use CContentDecorator:
$this->beginContent('path/to/view');
// ... content to be decorated
$this->endContent();

The property view specifies the name of the view that is used to decorate the content. In the view, the content being decorated may be accessed with variable $content.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
data | array | the variables (name=>value) to be extracted and made available in the decorative view. | CContentDecorator
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
view | mixed | the name of the view that will be used to decorate the captured content. | CContentDecorator
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | COutputProcessor
onProcessOutput() | Raised when the output has been captured. | COutputProcessor
processOutput() | Processes the captured output. | CContentDecorator
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | COutputProcessor
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
decorate() | Decorates the content by rendering a view and embedding the content in it. | CContentDecorator

Events

Hide inherited events

Event | Description | Defined By
onProcessOutput | Raised when the output has been captured. | COutputProcessor

Property Details

data property (available since v1.0.4)
public array $data;

the variables (name=>value) to be extracted and made available in the decorative view.

view property
public mixed $view;

the name of the view that will be used to decorate the captured content. If this property is null (default value), the default layout will be used as the decorative view. Note that if the current controller does not belong to any module, the default layout refers to the application's default layout; If the controller belongs to a module, the default layout refers to the module's default layout.

Method Details

decorate() method
protected string decorate(string $content)
$content | string | the content to be decorated
{return} | string | the decorated content

Decorates the content by rendering a view and embedding the content in it. The content being embedded can be accessed in the view using variable $content The decorated content will be displayed directly.

processOutput() method
public void processOutput(string $output)
$output string the captured output to be processed

Processes the captured output. This method decorates the output with the specified view.


CFilterWidget

Package | system.web.widgets
Inheritance | class CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Subclasses | COutputCache, COutputProcessor
Since | 1.0
Version | $Id: CFilterWidget.php 1678 2010-01-07 21:02:00Z qiang.xue $
CFilterWidget is the base class for widgets that can also be used as filters.

Derived classes may need to override the following methods:
  • CWidget::init() : called when this is object is used as a widget and needs initialization.
  • CWidget::run() : called when this is object is used as a widget.
  • filter() : the filtering method called when this object is used as an action filter.

CFilterWidget provides all properties and methods of CWidget and CFilter.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

isFilter property read-only (available since v1.0.4)
public boolean getIsFilter()

whether this widget is used as a filter.

stopAction property
public boolean $stopAction;

whether to stop the action execution when this widget is used as a filter. This property should be changed only in CWidget::init method. Defaults to false, meaning the action should be executed.

Method Details

__construct() method
public void __construct(CBaseController $owner=NULL)
$owner CBaseController owner/creator of this widget. It could be either a widget or a controller.

Constructor.

filter() method
public void filter(CFilterChain $filterChain)
$filterChain CFilterChain the filter chain that the filter is on.

Performs the filtering. The default implementation simply calls init(), CFilterChain::run() and run() in order Derived classes may want to override this method to change this behavior.

getIsFilter() method (available since v1.0.4)
public boolean getIsFilter()
{return} boolean whether this widget is used as a filter.


CFlexWidget

Package | system.web.widgets
Inheritance | class CFlexWidget » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CFlexWidget.php 1766 2010-02-01 00:27:29Z qiang.xue $
CFlexWidget embeds a Flex 3.x application into a page.

To use CFlexWidget, set name to be the Flex application name (without the .swf suffix), and set baseUrl to be URL (without the ending slash) of the directory containing the SWF file of the Flex application.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
align | string | align of the application region. | CFlexWidget
allowFullScreen | boolean | whether to allow running the Flash in full screen mode. | CFlexWidget
allowScriptAccess | string | the access method of the script. | CFlexWidget
altHtmlContent | string | the HTML content to be displayed if Flash player is not installed. | CFlexWidget
baseUrl | string | the base URL of the Flex application. | CFlexWidget
bgColor | string | background color of the application region. | CFlexWidget
controller | CController | the controller that this widget belongs to. | CWidget
enableHistory | boolean | whether history should be enabled. | CFlexWidget
flashVars | array | parameters to be passed to the Flex application. | CFlexWidget
flashVarsAsString | string | Generates the properly quoted flash parameter string. | CFlexWidget
height | string | height of the application region. | CFlexWidget
id | string | id of the widget. | CWidget
name | string | name of the Flex application. | CFlexWidget
owner | CBaseController | owner/creator of this widget. | CWidget
quality | string | quality of the animation. | CFlexWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget
width | string | width of the application region. | CFlexWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getFlashVarsAsString() | Generates the properly quoted flash parameter string. | CFlexWidget
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CFlexWidget
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the widget. | CFlexWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

align property
public string $align;

align of the application region. Defaults to 'middle'.

allowFullScreen property (available since v1.1.1)
public boolean $allowFullScreen;

whether to allow running the Flash in full screen mode. Defaults to false.

allowScriptAccess property
public string $allowScriptAccess;

the access method of the script. Defaults to 'sameDomain'.

altHtmlContent property
public string $altHtmlContent;

the HTML content to be displayed if Flash player is not installed.

baseUrl property
public string $baseUrl;

the base URL of the Flex application. This refers to the URL of the directory containing the SWF file.

bgColor property
public string $bgColor;

background color of the application region. Defaults to '#FFFFFF', meaning white.

enableHistory property
public boolean $enableHistory;

whether history should be enabled. Defaults to true.

flashVars property
public array $flashVars;

parameters to be passed to the Flex application.

flashVarsAsString property read-only
public string getFlashVarsAsString()

Generates the properly quoted flash parameter string.

height property
public string $height;

height of the application region. Defaults to 300.

name property
public string $name;

name of the Flex application. This should be the SWF file name without the ".swf" suffix.

quality property
public string $quality;

quality of the animation. Defaults to 'high'.

width property
public string $width;

width of the application region. Defaults to 450.

Method Details

getFlashVarsAsString() method
public string getFlashVarsAsString()
{return} string the flash parameter string.

Generates the properly quoted flash parameter string.

registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

run() method
public void run()

Renders the widget.


CHtmlPurifier

All Packages | Properties | Methods | Events
Package | system.web.widgets
Inheritance | class CHtmlPurifier » COutputProcessor » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CHtmlPurifier.php 1678 2010-01-07 21:02:00Z qiang.xue $
CHtmlPurifier is wrapper of HTML Purifier.

CHtmlPurifier removes all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist. It will also make sure the resulting code is standard-compliant.

CHtmlPurifier can be used as either a widget or a controller filter.

Note: since HTML Purifier is a big package, its performance is not very good. You should consider either caching the purification result or purifying the user input before saving to database.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
options | mixed | the options to be passed to {@link http://htmlpurifier. | CHtmlPurifier
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | COutputProcessor
onProcessOutput() | Raised when the output has been captured. | COutputProcessor
processOutput() | Processes the captured output. | CHtmlPurifier
purify() | Purifies the HTML content by removing malicious code. | CHtmlPurifier
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | COutputProcessor
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Events

Hide inherited events

Event | Description | Defined By
onProcessOutput | Raised when the output has been captured. | COutputProcessor

Property Details

options property
public mixed $options;

the options to be passed to HTML Purifier. This can be a HTMLPurifier_Config object, an array of directives (Namespace.Directive => Value) or the filename of an ini file.

See Also

  • http://htmlpurifier.org/live/configdoc/plain.html

Method Details

processOutput() method
public void processOutput(string $output)
$output string the captured output to be processed

Processes the captured output. This method purifies the output using HTML Purifier.

purify() method
public string purify(string $content)
$content | string | the content to be purified.
{return} | string | the purified content

Purifies the HTML content by removing malicious code.


CInputWidget

Package | system.web.widgets
Inheritance | abstract class CInputWidget » CWidget » CBaseController » CComponent
Subclasses | CAutoComplete, CMaskedTextField, CStarRating
Since | 1.0
Version | $Id: CInputWidget.php 1678 2010-01-07 21:02:00Z qiang.xue $
CInputWidget is the base class for widgets that collect user inputs.

CInputWidget declares properties common among input widgets. An input widget can be associated with a data model and an attribute, or a name and a value. If the former, the name and the value will be generated automatically. Child classes may use resolveNameID and hasModel.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CInputWidget
controller | CController | the controller that this widget belongs to. | CWidget
htmlOptions | array | additional HTML options to be rendered in the input tag | CInputWidget
id | string | id of the widget. | CWidget
model | CModel | the data model associated with this widget. | CInputWidget
name | string | the input name. | CInputWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
value | string | the input value | CInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
hasModel() |  | CInputWidget
resolveNameID() |  | CInputWidget

Property Details

attribute property
public string $attribute;

the attribute associated with this widget. Starting from version 1.0.9, the name can contain square brackets (e.g. 'name[1]') which is used to collect tabular data input.

htmlOptions property
public array $htmlOptions;

additional HTML options to be rendered in the input tag

model property
public CModel $model;

the data model associated with this widget.

name property
public string $name;

the input name. This must be set if model is not set.

value property
public string $value;

the input value

Method Details

hasModel() method
protected boolean hasModel()
{return} boolean whether this widget is associated with a data model.

resolveNameID() method
protected array resolveNameID()
{return} array the name and the ID of the input.


CMarkdown

All Packages | Properties | Methods | Events
Package | system.web.widgets
Inheritance | class CMarkdown » COutputProcessor » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CMarkdown.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMarkdown converts the captured content from markdown syntax to HTML code.

CMarkdown can be used as either a widget or a filter. It is a wrapper of CMarkdownParser. CMarkdown adds an additional option purifyOutput which can be set true so that the converted HTML code is purified before being displayed.

For details about the markdown syntax, please check the following:
  • official markdown syntax
  • markdown extra syntax
  • markdown with syntax highlighting

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CMarkdown
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
markdownParser |  | Returns the markdown parser instance. | CMarkdown
owner | CBaseController | owner/creator of this widget. | CWidget
purifyOutput | boolean | whether to use CHtmlPurifier to purify the generated HTML code. | CMarkdown
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getMarkdownParser() | Returns the markdown parser instance. | CMarkdown
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | COutputProcessor
onProcessOutput() | Raised when the output has been captured. | COutputProcessor
processOutput() | Processes the captured output. | CMarkdown
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CMarkdown
registerCssFile() | Registers the needed CSS file. | CMarkdown
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | COutputProcessor
setId() |  | CWidget
transform() | Converts the content in markdown syntax to HTML code. | CMarkdown
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
createMarkdownParser() | Creates a markdown parser. | CMarkdown

Events

Hide inherited events

Event | Description | Defined By
onProcessOutput | Raised when the output has been captured. | COutputProcessor

Property Details

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

markdownParser property read-only (available since v1.0.1)
public void getMarkdownParser()

Returns the markdown parser instance. This method calls createMarkdownParser to create the parser instance. Call this method multipe times will only return the same instance.

purifyOutput property
public boolean $purifyOutput;

whether to use CHtmlPurifier to purify the generated HTML code. Defaults to false.

Method Details

createMarkdownParser() method
protected CMarkdownParser createMarkdownParser()
{return} CMarkdownParser the markdown parser.

Creates a markdown parser. By default, this method creates a CMarkdownParser instance.

getMarkdownParser() method (available since v1.0.1)
public void getMarkdownParser()

Returns the markdown parser instance. This method calls createMarkdownParser to create the parser instance. Call this method multipe times will only return the same instance.

processOutput() method
public void processOutput(string $output)
$output string the captured output to be processed

Processes the captured output. This method converts the content in markdown syntax to HTML code. If purifyOutput is true, the HTML code will also be purified.

See Also

  • convert
registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.

transform() method
public string transform(string $output)
$output | string | the content to be converted
{return} | string | the converted content

Converts the content in markdown syntax to HTML code. This method uses CMarkdownParser to do the conversion.


CMaskedTextField

Package | system.web.widgets
Inheritance | class CMaskedTextField » CInputWidget » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CMaskedTextField.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMaskedTextField generates a masked text field.

CMaskedTextField is similar to CHtml::textField except that an input mask will be used to help users enter properly formatted data. The masked text field is implemented based on the jQuery masked input plugin (see http://digitalbush.com/projects/masked-input-plugin).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CInputWidget
charMap | array | the mapping between mask characters and the corresponding patterns. | CMaskedTextField
completed | string | a JavaScript function callback that will be invoked when user finishes the input. | CMaskedTextField
controller | CController | the controller that this widget belongs to. | CWidget
htmlOptions | array | additional HTML options to be rendered in the input tag | CInputWidget
id | string | id of the widget. | CWidget
mask | string | the input mask (e. | CMaskedTextField
model | CModel | the data model associated with this widget. | CInputWidget
name | string | the input name. | CInputWidget
owner | CBaseController | owner/creator of this widget. | CWidget
placeholder | string | the character prompting for user input. | CMaskedTextField
skin | mixed | the name of the skin to be used by this widget. | CWidget
value | string | the input value | CInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
clientOptions | array | the options for the text field | CMaskedTextField

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CMaskedTextField
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CMaskedTextField
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
getClientOptions() |  | CMaskedTextField
hasModel() |  | CInputWidget
resolveNameID() |  | CInputWidget

Property Details

charMap property
public array $charMap;

the mapping between mask characters and the corresponding patterns. For example, array('~'=>'[+-]') specifies that the '~' character expects '+' or '-' input. Defaults to null, meaning using the map as described in mask.

clientOptions property read-only
protected array getClientOptions()

the options for the text field

completed property
public string $completed;

a JavaScript function callback that will be invoked when user finishes the input.

mask property
public string $mask;

the input mask (e.g. '99/99/9999' for date input). The following characters are predefined:

  • a: represents an alpha character (A-Z,a-z)
  • 9: represents a numeric character (0-9)
  • *: represents an alphanumeric character (A-Z,a-z,0-9).
Additional characters can be defined by specifying the charMap property.

placeholder property
public string $placeholder;

the character prompting for user input. Defaults to underscore '_'.

Method Details

getClientOptions() method
protected array getClientOptions()
{return} array the options for the text field

registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

run() method
public void run()

Executes the widget. This method registers all needed client scripts and renders the text field.


CMultiFileUpload

Package | system.web.widgets
Inheritance | class CMultiFileUpload » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CMultiFileUpload.php 1678 2010-01-07 21:02:00Z qiang.xue $
CMultiFileUpload generates a file input that can allow uploading multiple files at a time.

This is based on the jQuery Multi File Upload plugin. The uploaded file information can be accessed via $_FILES[widget-name], which gives an array of the uploaded files. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
accept | string | the file types that are allowed (e. | CMultiFileUpload
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
denied | string | message that is displayed when a file type is not allowed. | CMultiFileUpload
duplicate | string | message that is displayed when a file appears twice. | CMultiFileUpload
htmlOptions | array | additional HTML attributes that will be rendered in the file upload tag. | CMultiFileUpload
id | string | id of the widget. | CWidget
max | integer | the maximum number of files that can be uploaded. | CMultiFileUpload
name | string | the input name. | CMultiFileUpload
owner | CBaseController | owner/creator of this widget. | CWidget
remove | string | the label for the remove button. | CMultiFileUpload
selected | string | message that is displayed when a file is selected. | CMultiFileUpload
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CMultiFileUpload
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Runs the widget. | CMultiFileUpload
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

accept property
public string $accept;

the file types that are allowed (e.g. "gif|jpg"). Note, the server side still needs to check if the uploaded files have allowed types.

denied property
public string $denied;

message that is displayed when a file type is not allowed.

duplicate property
public string $duplicate;

message that is displayed when a file appears twice.

htmlOptions property
public array $htmlOptions;

additional HTML attributes that will be rendered in the file upload tag.

max property
public integer $max;

the maximum number of files that can be uploaded. If -1, it means no limits. Defaults to -1.

name property
public string $name;

the input name.

remove property
public string $remove;

the label for the remove button. Defaults to "Remove".

selected property
public string $selected;

message that is displayed when a file is selected.

Method Details

registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

run() method
public void run()

Runs the widget. This method registers all needed client scripts and renders the multiple file uploader.


COutputCache

Package | system.web.widgets
Inheritance | class COutputCache » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: COutputCache.php 1678 2010-01-07 21:02:00Z qiang.xue $
COutputCache enables caching the output generated by an action or a view fragment.

If the output to be displayed is found valid in cache, the cached version will be displayed instead, which saves the time for generating the original output.

Since COutputCache extends from CFilterWidget, it can be used as either a filter (for action caching) or a widget (for fragment caching). For the latter, the shortcuts CBaseController::beginCache() and CBaseController::endCache() are often used instead, like the following in a view file:
if($this->beginCache('cacheName',array('property1'=>'value1',...))
{
    // ... display the content to be cached here
   $this->endCache();
}

COutputCache must work with a cache application component specified via cacheID. If the cache application component is not available, COutputCache will be disabled.

The validity of the cached content is determined based on two factors: the duration and the cache dependency. The former specifies the number of seconds that the data can remain valid in cache (defaults to 60s), while the latter specifies conditions that the cached data depends on. If a dependency changes, (e.g. relevant data in DB are updated), the cached data will be invalidated. For more details about cache dependency, see CCacheDependency.

Sometimes, it is necessary to turn off output caching only for certain request types. For exapmle, we only want to cache a form when it is initially requested; any subsequent display of the form should not be cached because it contains user input. We can set requestTypes to be array('GET') to accomplish this task.

The content fetched from cache may be variated with respect to some parameters. COutputCache supports two kinds of variations:
  • varyByRoute: this specifies whether the cached content should be varied with the requested route (controller and action)
  • varyByParam: this specifies a list of GET parameter names and uses the corresponding values to determine the version of the cached content.
  • varyBySession: this specifies whether the cached content should be varied with the user session.
  • varyByExpression: this specifies whether the cached content should be varied with the result of the specified PHP expression.
For more advanced variation, override getBaseCacheKey() method.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
cacheID | string | the ID of the cache application component. | COutputCache
controller | CController | the controller that this widget belongs to. | CWidget
dependency | mixed | the dependency that the cached content depends on. | COutputCache
duration | integer | number of seconds that the data can remain in cache. | COutputCache
id | string | id of the widget. | CWidget
isContentCached | boolean | whether the content can be found from cache | COutputCache
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
owner | CBaseController | owner/creator of this widget. | CWidget
requestTypes | array | list of request types (e. | COutputCache
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
varyByExpression | string | a PHP expression whose result is used in the cache key calculation. | COutputCache
varyByParam | array | list of GET parameters that should participate in cache key calculation. | COutputCache
varyByRoute | boolean | whether the content being cached should be differentiated according to route. | COutputCache
varyBySession | boolean | whether the content being cached should be differentiated according to user sessions. | COutputCache
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
baseCacheKey | string | Caclulates the base cache key. | COutputCache
cache | ICache | the cache used for caching the content. | COutputCache
cacheKey | string | Calculates the cache key. | COutputCache

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs filtering before the action is executed. | COutputCache
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsContentCached() |  | COutputCache
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Marks the start of content to be cached. | COutputCache
raiseEvent() | Raises an event. | CComponent
recordAction() | Records a method call when this output cache is in effect. | COutputCache
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Marks the end of content to be cached. | COutputCache
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
checkContentCache() | Looks for content in cache. | COutputCache
getBaseCacheKey() | Caclulates the base cache key. | COutputCache
getCache() |  | COutputCache
getCacheKey() | Calculates the cache key. | COutputCache
replayActions() | Replays the recorded method calls. | COutputCache

Property Details

baseCacheKey property read-only
protected string getBaseCacheKey()

Caclulates the base cache key. The calculated key will be further variated in getCacheKey. Derived classes may override this method if more variations are needed.

cache property read-only
protected ICache getCache()

the cache used for caching the content.

cacheID property
public string $cacheID;

the ID of the cache application component. Defaults to 'cache' (the primary cache application component.)

cacheKey property read-only
protected string getCacheKey()

Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam and varyBySession.

dependency property
public mixed $dependency;

the dependency that the cached content depends on. This can be either an object implementing ICacheDependency interface or an array specifying the configuration of the dependency object. For example,

array(
    'class'=>'CDbCacheDependency',
    'sql'=>'SELECT MAX(lastModified) FROM Post',
)
would make the output cache depends on the last modified time of all posts. If any post has its modification time changed, the cached content would be invalidated.

duration property
public integer $duration;

number of seconds that the data can remain in cache. Defaults to 60 seconds. If 0 or negative, it means the cache is disabled. Note, if cache dependency changes or cache space is limited, the data may be purged out of cache earlier.

isContentCached property read-only
public boolean getIsContentCached()

whether the content can be found from cache

requestTypes property
public array $requestTypes;

list of request types (e.g. GET, POST) for which the cache should be enabled only. Defaults to null, meaning all request types.

varyByExpression property (available since v1.0.4)
public string $varyByExpression;

a PHP expression whose result is used in the cache key calculation. By setting this property, the output cache will use different cached data for each different expression result. Starting from version 1.0.11, the expression can also be a valid PHP callback, including class method name (array(ClassName/Object, MethodName)), or anonymous function (PHP 5.3.0+). The function/method signature should be as follows:

function foo($cache) { ... }
where $cache refers to the output cache component.

varyByParam property
public array $varyByParam;

list of GET parameters that should participate in cache key calculation. By setting this property, the output cache will use different cached data for each different set of GET parameter values.

varyByRoute property
public boolean $varyByRoute;

whether the content being cached should be differentiated according to route. A route consists of the requested controller ID and action ID. Defaults to true.

varyBySession property
public boolean $varyBySession;

whether the content being cached should be differentiated according to user sessions. Defaults to false.

Method Details

checkContentCache() method
protected boolean checkContentCache()
{return} boolean whether the content is found in cache.

Looks for content in cache.

filter() method
public boolean filter($filterChain)
$filterChain |  |
{return} | boolean | whether the filtering process should stop after this filter. Defaults to false.

Performs filtering before the action is executed. This method is meant to be overridden by child classes if begin-filtering is needed.

getBaseCacheKey() method
protected string getBaseCacheKey()
{return} string basic cache key without variations

Caclulates the base cache key. The calculated key will be further variated in getCacheKey. Derived classes may override this method if more variations are needed.

getCache() method
protected ICache getCache()
{return} ICache the cache used for caching the content.

getCacheKey() method
protected string getCacheKey()
{return} string cache key

Calculates the cache key. The key is calculated based on getBaseCacheKey and other factors, including varyByRoute, varyByParam and varyBySession.

getIsContentCached() method
public boolean getIsContentCached()
{return} boolean whether the content can be found from cache

init() method
public void init()

Marks the start of content to be cached. Content displayed after this method call and before endCache() will be captured and saved in cache. This method does nothing if valid content is already found in cache.

recordAction() method
public void recordAction(string $context, string $method, array $params)
$context | string | a property name of the controller. The property should refer to an object whose method is being recorded. If empty it means the controller itself.
$method | string | the method name
$params | array | parameters passed to the method

Records a method call when this output cache is in effect. When the content is served from the output cache, the recorded method will be re-invoked.

replayActions() method
protected void replayActions()

Replays the recorded method calls.

run() method
public void run()

Marks the end of content to be cached. Content displayed before this method call and after init() will be captured and saved in cache. This method does nothing if valid content is already found in cache.


COutputProcessor

All Packages | Properties | Methods | Events
Package | system.web.widgets
Inheritance | class COutputProcessor » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Subclasses | CContentDecorator, CHtmlPurifier, CMarkdown, CTextHighlighter
Since | 1.0
Version | $Id: COutputProcessor.php 1678 2010-01-07 21:02:00Z qiang.xue $
COutputProcessor transforms the content into a different format.

COutputProcessor captures the output generated by an action or a view fragment and passes it to its onProcessOutput event handlers for further processing.

The event handler may process the output and store it back to the COutputEvent::output property. By setting the handled property of the event parameter to true, the output will not be echoed anymore. Otherwise (by default), the output will be echoed.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | COutputProcessor
onProcessOutput() | Raised when the output has been captured. | COutputProcessor
processOutput() | Processes the captured output. | COutputProcessor
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | COutputProcessor
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Events

Hide inherited events

Event | Description | Defined By
onProcessOutput | Raised when the output has been captured. | COutputProcessor

Method Details

init() method
public void init()

Initializes the widget. This method starts the output buffering.

onProcessOutput() method
public void onProcessOutput(COutputEvent $event)
$event COutputEvent event parameter

Raised when the output has been captured.

processOutput() method
public void processOutput(string $output)
$output string the captured output to be processed

Processes the captured output.

The default implementation raises an onProcessOutput event. If the event is not handled by any event handler, the output will be echoed.

run() method
public void run()

Executes the widget. This method stops output buffering and processes the captured output.


CStarRating

Package | system.web.widgets
Inheritance | class CStarRating » CInputWidget » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CStarRating.php 1678 2010-01-07 21:02:00Z qiang.xue $
CStarRating displays a star rating control that can collect user rating input.

CStarRating is based on jQuery Star Rating Plugin. It displays a list of stars indicating the rating values. Users can toggle these stars to indicate their rating input. On the server side, when the rating input is submitted, the value can be retrieved in the same way as working with a normal HTML input. For example, using
$this->widget('CStarRating',array('name'=>'rating'));
we can retrieve the rating value via $_POST['rating'].

CStarRating allows customization of its appearance. It also supports empty rating as well as read-only rating.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
allowEmpty | boolean | whether the rating value can be empty (not set). | CStarRating
attribute | string | the attribute associated with this widget. | CInputWidget
blur | string | Callback when the stars are not focused. | CStarRating
callback | string | Callback when the stars are clicked. | CStarRating
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CStarRating
focus | string | Callback when the stars are focused. | CStarRating
htmlOptions | array | additional HTML options to be rendered in the input tag | CInputWidget
id | string | id of the widget. | CWidget
maxRating | mixed | the maximum rating allowed. | CStarRating
minRating | mixed | the minimum rating allowed. | CStarRating
model | CModel | the data model associated with this widget. | CInputWidget
name | string | the input name. | CInputWidget
owner | CBaseController | owner/creator of this widget. | CWidget
ratingStepSize | mixed | the step size of rating. | CStarRating
readOnly | boolean | whether the rating value is read-only or not. | CStarRating
resetText | string | the hint text for the reset button. | CStarRating
resetValue | string | the value taken when the rating is cleared. | CStarRating
skin | mixed | the name of the skin to be used by this widget. | CWidget
starCount | integer | the number of stars. | CStarRating
starWidth | integer | the width of star image. | CStarRating
titles | array | the titles associated with the rating options. | CStarRating
value | string | the input value | CInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
clientOptions | array | the javascript options for the star rating | CStarRating

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the necessary javascript and css scripts. | CStarRating
registerCssFile() | Registers the needed CSS file. | CStarRating
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CStarRating
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
getClientOptions() |  | CStarRating
hasModel() |  | CInputWidget
renderStars() | Renders the stars. | CStarRating
resolveNameID() |  | CInputWidget

Property Details

allowEmpty property
public boolean $allowEmpty;

whether the rating value can be empty (not set). Defaults to true. When this is true, a reset button will be displayed in front of stars.

blur property
public string $blur;

Callback when the stars are not focused.

callback property
public string $callback;

Callback when the stars are clicked.

clientOptions property read-only
protected array getClientOptions()

the javascript options for the star rating

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

focus property
public string $focus;

Callback when the stars are focused.

maxRating property
public mixed $maxRating;

the maximum rating allowed. This can be either an integer or a double value. Defaults to 1.

minRating property
public mixed $minRating;

the minimum rating allowed. This can be either an integer or a double value. Defaults to 1.

ratingStepSize property
public mixed $ratingStepSize;

the step size of rating. This is the minimum difference between two rating values. Defaults to 1.

readOnly property
public boolean $readOnly;

whether the rating value is read-only or not. Defaults to false. When this is true, the rating cannot be changed.

resetText property
public string $resetText;

the hint text for the reset button. Defaults to null, meaning using the system-defined text (which is 'Cancel Rating').

resetValue property
public string $resetValue;

the value taken when the rating is cleared. Defaults to null, meaning using the system-defined value (which is '').

starCount property
public integer $starCount;

the number of stars. Defaults to 5.

starWidth property
public integer $starWidth;

the width of star image. Defaults to null, meaning using the system-defined value (which is 16).

titles property
public array $titles;

the titles associated with the rating options. The keys are ratings and the values are the corresponding titles. Defaults to null, meaning using the rating value as the title.

Method Details

getClientOptions() method
protected array getClientOptions()
{return} array the javascript options for the star rating

registerClientScript() method
public void registerClientScript(string $id)
$id string the ID of the container

Registers the necessary javascript and css scripts.

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.

renderStars() method
protected void renderStars(string $id, string $name)
$id | string | the ID of the container
$name | string | the name of the input

Renders the stars.

run() method
public void run()

Executes the widget. This method registers all needed client scripts and renders the text field.


CTabView

Package | system.web.widgets
Inheritance | class CTabView » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CTabView.php 1868 2010-03-09 21:34:27Z qiang.xue $
CTabView displays contents in multiple tabs.

At any time, only one tab is visible. Users can click on the tab header to switch to see another tab of content.

JavaScript is used to control the tab switching. If JavaScript is disabled, CTabView still manages to display the content in a semantically appropriate way.

To specify contents and their tab structure, configure the tabs property. The tabs property takes an array with tab ID being mapped tab definition. Each tab definition is an array of the following structure:
  • title: the tab title.
  • content: the content to be displayed in the tab.
  • view: the name of the view to be displayed in this tab. The view will be rendered using the current controller's CController::renderPartial method. When both 'content' and 'view' are specified, 'content' will take precedence.
  • url: a URL that the user browser will be redirected to when clicking on this tab.
  • data: array (name=>value), this will be passed to the view when 'view' is specified.

For example, the tabs property can be configured as follows,
array(
    'tab1'=>array(
          'title'=>'tab 1 title',
          'view'=>'view1',
          'data'=>array('model'=>$model),
    ),
    'tab2'=>array(
          'title'=>'tab 2 title',
          'url'=>'http://www.yiiframework.com/',
    ),
)

By default, the first tab will be activated. To activate a different tab when the page is initially loaded, set activeTab to be the ID of the desired tab.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
activeTab | string | the ID of the tab that should be activated when the page is initially loaded. | CTabView
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CTabView
htmlOptions | array | additional HTML options to be rendered in the container tag. | CTabView
id | string | id of the widget. | CWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tabs | array | tab definitions. | CTabView
viewData | array | the data that will be passed to the partial view rendered by each tab. | CTabView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CTabView
registerCssFile() | Registers the needed CSS file. | CTabView
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Runs the widget. | CTabView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderBody() | Renders the body part. | CTabView
renderHeader() | Renders the header part. | CTabView

Property Details

activeTab property
public string $activeTab;

the ID of the tab that should be activated when the page is initially loaded. If not set, the first tab will be activated.

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

htmlOptions property
public array $htmlOptions;

additional HTML options to be rendered in the container tag.

tabs property
public array $tabs;

tab definitions. The array keys are the IDs, and the array values are the corresponding tab contents. Each array value must be an array with the following elements:

  • title: the tab title. You need to make sure this is HTML-encoded.
  • content: the content to be displayed in the tab.
  • view: the name of the view to be displayed in this tab. The view will be rendered using the current controller's CController::renderPartial method. When both 'content' and 'view' are specified, 'content' will take precedence.
  • url: a URL that the user browser will be redirected to when clicking on this tab.
  • data: array (name=>value), this will be passed to the view when 'view' is specified. This option is available since version 1.1.1.
array(
    'tab1'=>array(
          'title'=>'tab 1 title',
          'view'=>'view1',
    ),
    'tab2'=>array(
          'title'=>'tab 2 title',
          'url'=>'http://www.yiiframework.com/',
    ),
)

viewData property
public array $viewData;

the data that will be passed to the partial view rendered by each tab.

Method Details

registerClientScript() method
public void registerClientScript()

Registers the needed CSS and JavaScript.

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.

renderBody() method
protected void renderBody()

Renders the body part.

renderHeader() method
protected void renderHeader()

Renders the header part.

run() method
public void run()

Runs the widget.


CTextHighlighter

All Packages | Properties | Methods | Events
Package | system.web.widgets
Inheritance | class CTextHighlighter » COutputProcessor » CFilterWidget » CWidget » CBaseController » CComponent
Implements | IFilter
Since | 1.0
Version | $Id: CTextHighlighter.php 1678 2010-01-07 21:02:00Z qiang.xue $
CTextHighlighter does syntax highlighting for its body content.

The language of the syntax to be applied is specified via language property. Currently, CTextHighlighter supports the following languages: ABAP, CPP, CSS, DIFF, DTD, HTML, JAVA, JAVASCRIPT, MYSQL, PERL, PHP, PYTHON, RUBY, SQL, XML. By setting showLineNumbers to true, the highlighted result may be shown with line numbers.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
containerOptions | array | the HTML attributes to be applied to the container element. | CTextHighlighter
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CTextHighlighter
id | string | id of the widget. | CWidget
isFilter | boolean | whether this widget is used as a filter. | CFilterWidget
language | string | the language whose syntax is to be used for highlighting. | CTextHighlighter
lineNumberStyle | string | the style of line number display. | CTextHighlighter
owner | CBaseController | owner/creator of this widget. | CWidget
showLineNumbers | boolean | whether to show line numbers in the highlighted result. | CTextHighlighter
skin | mixed | the name of the skin to be used by this widget. | CWidget
stopAction | boolean | whether to stop the action execution when this widget is used as a filter. | CFilterWidget
tabSize | integer | tab size. | CTextHighlighter
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CFilterWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
filter() | Performs the filtering. | CFilterWidget
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getIsFilter() |  | CFilterWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
highlight() | Highlights the content by the syntax of the specified language. | CTextHighlighter
init() | Initializes the widget. | COutputProcessor
onProcessOutput() | Raised when the output has been captured. | COutputProcessor
processOutput() | Processes the captured output. | CTextHighlighter
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed CSS and JavaScript. | CTextHighlighter
registerCssFile() | Registers the needed CSS file. | CTextHighlighter
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | COutputProcessor
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Events

Hide inherited events

Event | Description | Defined By
onProcessOutput | Raised when the output has been captured. | COutputProcessor

Property Details

containerOptions property
public array $containerOptions;

the HTML attributes to be applied to the container element. The highlighted content is contained in a DIV element.

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

language property
public string $language;

the language whose syntax is to be used for highlighting. Valid values are those file names (without suffix) that are contained in 'vendors/TextHighlighter/Text/Highlighter'. Currently, the following languages are supported: ABAP, CPP, CSS, DIFF, DTD, HTML, JAVA, JAVASCRIPT, MYSQL, PERL, PHP, PYTHON, RUBY, SQL, XML If a language is not supported, it will be displayed as plain text. Language names are case-insensitive.

lineNumberStyle property
public string $lineNumberStyle;

the style of line number display. It can be either 'list' or 'table'. Defaults to 'list'.

See Also

  • showLineNumbers
showLineNumbers property
public boolean $showLineNumbers;

whether to show line numbers in the highlighted result. Defaults to false.

See Also

  • lineNumberStyle
tabSize property
public integer $tabSize;

tab size. Defaults to 4.

Method Details

highlight() method
public string highlight(string $content)
$content | string | the content to be highlighted.
{return} | string | the highlighted content

Highlights the content by the syntax of the specified language.

processOutput() method
public void processOutput(string $output)
$output string the captured output to be processed

Processes the captured output. This method highlights the output according to the syntax of the specified language.

registerClientScript() method (available since v1.0.1)
public void registerClientScript()

Registers the needed CSS and JavaScript.

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.


CTreeView

Package | system.web.widgets
Inheritance | class CTreeView » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CTreeView.php 1839 2010-02-26 04:08:14Z qiang.xue $
CTreeView displays a tree view of hierarchical data.

It encapsulates the excellent tree view plugin for jQuery (http://bassistance.de/jquery-plugins/jquery-plugin-treeview/).

To use CTreeView, simply sets data to the data that you want to present and you are there.

CTreeView also supports dynamic data loading via AJAX. To do so, set url to be the URL that can serve the tree view data upon request.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
animated | string|integer | animation speed. | CTreeView
collapsed | boolean | whether the tree should start with all branches collapsed. | CTreeView
control | string | container for a tree-control, allowing the user to expand, collapse and toggle all branches with one click. | CTreeView
controller | CController | the controller that this widget belongs to. | CWidget
cookieId | string | The cookie name to use when persisting via persist:"cookie". | CTreeView
cssFile | mixed | the CSS file used for the widget. | CTreeView
data | array | the data that can be used to generate the tree view content. | CTreeView
htmlOptions | array | additional HTML attributes that will be rendered in the UL tag. | CTreeView
id | string | id of the widget. | CWidget
options | array | additional options that can be passed to the constructor of the treeview js object. | CTreeView
owner | CBaseController | owner/creator of this widget. | CWidget
persist | string | Persist the tree state in cookies or the page location. | CTreeView
prerendered | boolean | Set to skip rendering of classes and hitarea divs, assuming that is done by the serverside. | CTreeView
skin | mixed | the name of the skin to be used by this widget. | CWidget
toggle | string | Callback when toggling a branch. | CTreeView
unique | boolean | set to allow only one branch on one level to be open (closing siblings which opening). | CTreeView
url | string|array | the URL to which the treeview can be dynamically loaded (in AJAX). | CTreeView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
clientOptions | array | the javascript options | CTreeView

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CTreeView
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Ends running the widget. | CTreeView
saveDataAsHtml() | Generates tree view nodes in HTML from the data array. | CTreeView
saveDataAsJson() | Saves tree view data in JSON format. | CTreeView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
getClientOptions() |  | CTreeView

Property Details

animated property
public string|integer $animated;

animation speed. This can be one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). If not set, no animation is used.

clientOptions property read-only
protected array getClientOptions()

the javascript options

collapsed property
public boolean $collapsed;

whether the tree should start with all branches collapsed. Defaults to false.

control property
public string $control;

container for a tree-control, allowing the user to expand, collapse and toggle all branches with one click. In the container, clicking on the first hyperlink will collapse the tree; the second hyperlink will expand the tree; while the third hyperlink will toggle the tree. The property should be a valid jQuery selector (e.g. '#treecontrol' where 'treecontrol' is the ID of the 'div' element containing the hyperlinks.)

cookieId property
public string $cookieId;

The cookie name to use when persisting via persist:"cookie". Defaults to 'treeview'.

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

data property
public array $data;

the data that can be used to generate the tree view content. Each array element corresponds to a tree view node with the following structure:

  • text: string, required, the HTML text associated with this node.
  • expanded: boolean, optional, whether the tree view node is in expanded.
  • id: string, optional, the ID identifying the node. This is used in dynamic loading of tree view (see url).
  • hasChildren: boolean, optional, defaults to false, whether clicking on this node should trigger dynamic loading of more tree view nodes from server. The url property must be set in order to make this effective.
  • children: array, optional, child nodes of this node.
Note, anything enclosed between the beginWidget and endWidget calls will also be treated as tree view content, which appends to the content generated from this data.

htmlOptions property
public array $htmlOptions;

additional HTML attributes that will be rendered in the UL tag. The default tree view CSS has defined the following CSS classes which can be enabled by specifying the 'class' option here:

  • treeview-black
  • treeview-gray
  • treeview-red
  • treeview-famfamfam
  • filetree

options property
public array $options;

additional options that can be passed to the constructor of the treeview js object.

persist property
public string $persist;

Persist the tree state in cookies or the page location. If set to "location", looks for the anchor that matches location.href and activates that part of the treeview it. Great for href-based state-saving. If set to "cookie", saves the state of the tree on each click to a cookie and restores that state on page load.

prerendered property
public boolean $prerendered;

Set to skip rendering of classes and hitarea divs, assuming that is done by the serverside. Defaults to false.

toggle property
public string $toggle;

Callback when toggling a branch. Arguments: "this" refers to the UL that was shown or hidden

unique property
public boolean $unique;

set to allow only one branch on one level to be open (closing siblings which opening). Defaults to false.

url property
public string|array $url;

the URL to which the treeview can be dynamically loaded (in AJAX). See CHtml::normalizeUrl for possible URL formats. Setting this property will enable the dynamic treeview loading. When the page is displayed, the browser will request this URL with a GET parameter named 'root' whose value is 'source'. The server script should then generate the needed tree view data corresponding to the root of the tree (see saveDataAsJson.) When a node has a CSS class 'hasChildren', then expanding this node will also cause a dynamic loading of its child nodes. In this case, the value of the 'root' GET parameter is the 'id' property of the node.

Method Details

getClientOptions() method
protected array getClientOptions()
{return} array the javascript options

init() method
public void init()

Initializes the widget. This method registers all needed client scripts and renders the tree view content.

run() method
public void run()

Ends running the widget.

saveDataAsHtml() method
public static string saveDataAsHtml(array $data)
$data | array | the data for the tree view (see data for possible data structure).
{return} | string | the generated HTML for the tree view

Generates tree view nodes in HTML from the data array.

saveDataAsJson() method
public static string saveDataAsJson(array $data)
$data | array | the data for the tree view (see data for possible data structure).
{return} | string | the JSON representation of the data

Saves tree view data in JSON format. This method is typically used in dynamic tree view loading when the server code needs to send to the client the dynamic tree view data.


CWidget

Package | system.web.widgets
Inheritance | class CWidget » CBaseController » CComponent
Subclasses | CActiveForm, CBaseListView, CBasePager, CBreadcrumbs, CCaptcha, CClipWidget, CDetailView, CFilterWidget, CFlexWidget, CInputWidget, CJuiWidget, CMenu, CMultiFileUpload, CPortlet, CTabView, CTreeView
Since | 1.0
Version | $Id: CWidget.php 1678 2010-01-07 21:02:00Z qiang.xue $
CWidget is the base class for widgets.

A widget is a self-contained component that may generate presentation based on model data. It can be viewed as a micro-controller that embeds into the controller-managed views.

Compared with controller, a widget has neither actions nor filters.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

actionPrefix property (available since v1.0.1)
public string $actionPrefix;

the prefix to the IDs of the actions. When a widget is declared an action provider in CController::actions, a prefix can be specified to differentiate its action IDs from others. The same prefix should then also be used to configure this property when the widget is used in a view of the controller.

controller property read-only
public CController getController()

the controller that this widget belongs to.

id property
public string getId(boolean $autoGenerate=true)
public void setId(string $value)

id of the widget.

owner property read-only
public CBaseController getOwner()

owner/creator of this widget. It could be either a widget or a controller.

skin property (available since v1.1)
public mixed $skin;

the name of the skin to be used by this widget. Defaults to 'default'. If this is set as false, no skin will be applied to this widget.

See Also

  • CWidgetFactory
viewPath property read-only
public string getViewPath()

Returns the directory containing the view files for this widget. The default implementation returns the 'views' subdirectory of the directory containing the widget class file.

Method Details

__construct() method
public void __construct(CBaseController $owner=NULL)
$owner CBaseController owner/creator of this widget. It could be either a widget or a controller.

Constructor.

actions() method (available since v1.0.1)
public static void actions()

Returns a list of actions that are used by this widget. The structure of this method's return value is similar to that returned by CController::actions.

When a widget uses several actions, you can declare these actions using this method. The widget will then become an action provider, and the actions can be easily imported into a controller.

Note, when creating URLs referring to the actions listed in this method, make sure the action IDs are prefixed with actionPrefix.

See Also

  • actionPrefix
  • CController::actions
getController() method
public CController getController()
{return} CController the controller that this widget belongs to.

getId() method
public string getId(boolean $autoGenerate=true)
$autoGenerate | boolean | whether to generate an ID if it is not set previously
{return} | string | id of the widget.

getOwner() method
public CBaseController getOwner()
{return} CBaseController owner/creator of this widget. It could be either a widget or a controller.

getViewFile() method
public string getViewFile(string $viewName)
$viewName | string | name of the view (without file extension)
{return} | string | the view file path. False if the view file does not exist

Looks for the view script file according to the view name. This method will look for the view under the widget's viewPath. The view script file is named as "ViewName.php". A localized view file may be returned if internationalization is needed. See CApplication::findLocalizedFile for more details. Since version 1.0.2, the view name can also refer to a path alias if it contains dot characters.

See Also

  • CApplication::findLocalizedFile
getViewPath() method
public string getViewPath()
{return} string the directory containing the view files for this widget.

Returns the directory containing the view files for this widget. The default implementation returns the 'views' subdirectory of the directory containing the widget class file.

init() method
public void init()

Initializes the widget. This method is called by CBaseController::createWidget and CBaseController::beginWidget after the widget's properties have been initialized.

render() method
public string render(string $view, array $data=NULL, boolean $return=false)
$view | string | name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data | array | data to be extracted into PHP variables and made available to the view script
$return | boolean | whether the rendering result should be returned instead of being displayed to end users
{return} | string | the rendering result. Null if the rendering result is not required.

Renders a view.

The named view refers to a PHP script (resolved via getViewFile) that is included by this method. If $data is an associative array, it will be extracted as PHP variables and made available to the script.

See Also

  • getViewFile
run() method
public void run()

Executes the widget. This method is called by CBaseController::endWidget.

setId() method
public void setId(string $value)
$value string id of the widget.


CCaptcha

Package | system.web.widgets.captcha
Inheritance | class CCaptcha » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CCaptcha.php 1678 2010-01-07 21:02:00Z qiang.xue $
CCaptcha renders a CAPTCHA image element.

CCaptcha is used together with CCaptchaAction to provide CAPTCHA - a way of preventing site spam.

The image element rendered by CCaptcha will display a CAPTCHA image generated by an action of class CCaptchaAction belonging to the current controller. By default, the action ID should be 'captcha', which can be changed by setting captchaAction.

CCaptcha may also render a button next to the CAPTCHA image. Clicking on the button will change the CAPTCHA image to be a new one in an AJAX way.

Since version 1.0.8, if clickableImage is set true, clicking on the CAPTCHA image will refresh the CAPTCHA.

A CCaptchaValidator may be used to validate that the user enters a verification code matching the code displayed in the CAPTCHA image.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
buttonLabel | string | the label for the refresh button. | CCaptcha
buttonOptions | array | HTML attributes to be applied to the rendered refresh button element. | CCaptcha
buttonType | string | the type of the refresh button. | CCaptcha
captchaAction | string | the ID of the action that should provide CAPTCHA image. | CCaptcha
clickableImage | boolean | whether to allow clicking on the CAPTCHA image to refresh the CAPTCHA letters. | CCaptcha
controller | CController | the controller that this widget belongs to. | CWidget
id | string | id of the widget. | CWidget
imageOptions | array | HTML attributes to be applied to the rendered image element. | CCaptcha
owner | CBaseController | owner/creator of this widget. | CWidget
showRefreshButton | boolean | whether to display a button next to the CAPTCHA image. | CCaptcha
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed client scripts. | CCaptcha
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the widget. | CCaptcha
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderImage() | Renders the CAPTCHA image. | CCaptcha

Property Details

buttonLabel property
public string $buttonLabel;

the label for the refresh button. Defaults to 'Get a new code'.

buttonOptions property
public array $buttonOptions;

HTML attributes to be applied to the rendered refresh button element.

buttonType property
public string $buttonType;

the type of the refresh button. This should be either 'link' or 'button'. The former refers to hyperlink button while the latter a normal push button. Defaults to 'link'.

captchaAction property
public string $captchaAction;

the ID of the action that should provide CAPTCHA image. Defaults to 'captcha', meaning the 'captcha' action of the current controller. This property may also be in the format of 'ControllerID/ActionID'. Underneath, this property is used by CController::createUrl to create the URL that would serve the CAPTCHA image. The action has to be of CCaptchaAction.

clickableImage property (available since v1.0.8)
public boolean $clickableImage;

whether to allow clicking on the CAPTCHA image to refresh the CAPTCHA letters. Defaults to false. Hint: you may want to set showRefreshButton to false if you set this property to be true because they serve for the same purpose. To enhance accessibility, you may set imageOptions to provide hints to end-users that the image is clickable.

imageOptions property
public array $imageOptions;

HTML attributes to be applied to the rendered image element.

showRefreshButton property
public boolean $showRefreshButton;

whether to display a button next to the CAPTCHA image. Clicking on the button will cause the CAPTCHA image to be changed to a new one. Defaults to true.

Method Details

registerClientScript() method (available since v1.0.2)
public void registerClientScript()

Registers the needed client scripts.

renderImage() method
protected void renderImage()

Renders the CAPTCHA image.

run() method
public void run()

Renders the widget.


CCaptchaAction

Package | system.web.widgets.captcha
Inheritance | class CCaptchaAction » CAction » CComponent
Implements | IAction
Since | 1.0
Version | $Id: CCaptchaAction.php 1696 2010-01-10 13:16:22Z qiang.xue $
CCaptchaAction renders a CAPTCHA image.

CCaptchaAction is used together with CCaptcha and CCaptchaValidator to provide the CAPTCHA feature.

You must configure properties of CCaptchaAction to customize the appearance of the generated image.

Note, CCaptchaAction requires PHP GD2 extension.

Using CAPTCHA involves the following steps:
  1. Override CController::actions() and register an action of class CCaptchaAction with ID 'captcha'.
  2. In the form model, declare an attribute to store user-entered verification code, and declare the attribute to be validated by the 'captcha' validator.
  3. In the controller view, insert a CCaptcha widget in the form.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
backColor | integer | the background color. | CCaptchaAction
controller | CController | the controller who owns this action. | CAction
fontFile | string | the TrueType font file. | CCaptchaAction
foreColor | integer | the font color. | CCaptchaAction
height | integer | the height of the generated CAPTCHA image. | CCaptchaAction
id | string | id of this action | CAction
maxLength | integer | the maximum length for randomly generated word. | CCaptchaAction
minLength | integer | the minimum length for randomly generated word. | CCaptchaAction
padding | integer | padding around the text. | CCaptchaAction
testLimit | integer | how many times should the same CAPTCHA be displayed. | CCaptchaAction
transparent | boolean | whether to use transparent background. | CCaptchaAction
verifyCode | string | Gets the verification code. | CCaptchaAction
width | integer | the width of the generated CAPTCHA image. | CCaptchaAction

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
sessionKey | string | Returns the session variable name used to store verification code. | CCaptchaAction

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CAction
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CAction
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CAction
getVerifyCode() | Gets the verification code. | CCaptchaAction
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
run() | Runs the action. | CCaptchaAction
validate() | Validates the input to see if it matches the generated code. | CCaptchaAction

Protected Methods

Hide inherited methods

Method | Description | Defined By
generateVerifyCode() | Generates a new verification code. | CCaptchaAction
getSessionKey() | Returns the session variable name used to store verification code. | CCaptchaAction
renderImage() | Renders the CAPTCHA image based on the code. | CCaptchaAction

Property Details

backColor property
public integer $backColor;

the background color. For example, 0x55FF00. Defaults to 0xFFFFFF, meaning white color.

fontFile property
public string $fontFile;

the TrueType font file. Defaults to Duality.ttf which is provided with the Yii release.

foreColor property
public integer $foreColor;

the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).

height property
public integer $height;

the height of the generated CAPTCHA image. Defaults to 50.

maxLength property
public integer $maxLength;

the maximum length for randomly generated word. Defaults to 7.

minLength property
public integer $minLength;

the minimum length for randomly generated word. Defaults to 6.

padding property
public integer $padding;

padding around the text. Defaults to 2.

sessionKey property read-only
protected string getSessionKey()

Returns the session variable name used to store verification code.

testLimit property
public integer $testLimit;

how many times should the same CAPTCHA be displayed. Defaults to 3.

transparent property (available since v1.0.10)
public boolean $transparent;

whether to use transparent background. Defaults to false.

verifyCode property read-only
public string getVerifyCode(string $regenerate=false)

Gets the verification code.

width property
public integer $width;

the width of the generated CAPTCHA image. Defaults to 120.

Method Details

generateVerifyCode() method
protected string generateVerifyCode()
{return} string the generated verification code

Generates a new verification code.

getSessionKey() method
protected string getSessionKey()
{return} string the session variable name

Returns the session variable name used to store verification code.

getVerifyCode() method
public string getVerifyCode(string $regenerate=false)
$regenerate | string | whether the verification code should be regenerated.
{return} | string | the verification code.

Gets the verification code.

renderImage() method
protected string renderImage(string $code)
$code | string | the verification code
{return} | string | image content

Renders the CAPTCHA image based on the code.

run() method
public void run()

Runs the action. If the GET parameter wsdlVar exists, the action will serve WSDL content; If not, the action will handle the remote method invocation.

validate() method
public whether validate(string $input, boolean $caseSensitive)
$input | string | user input
$caseSensitive | boolean | whether the comparison should be case-sensitive
{return} | whether | the input is valid

Validates the input to see if it matches the generated code.


CBasePager

Package | system.web.widgets.pagers
Inheritance | abstract class CBasePager » CWidget » CBaseController » CComponent
Subclasses | CLinkPager, CListPager
Since | 1.0
Version | $Id: CBasePager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CBasePager is the base class for all pagers.

It provides the calculation of page count and maintains the current page.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
currentPage | integer | the zero-based index of the current page. | CBasePager
id | string | id of the widget. | CWidget
itemCount | integer | total number of items. | CBasePager
owner | CBaseController | owner/creator of this widget. | CWidget
pageCount | integer | number of pages | CBasePager
pageSize | integer | number of items in each page. | CBasePager
pages | CPagination | Returns the pagination information used by this pager. | CBasePager
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getCurrentPage() |  | CBasePager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getItemCount() |  | CBasePager
getOwner() |  | CWidget
getPageCount() |  | CBasePager
getPageSize() |  | CBasePager
getPages() | Returns the pagination information used by this pager. | CBasePager
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setCurrentPage() |  | CBasePager
setId() |  | CWidget
setItemCount() |  | CBasePager
setPageSize() |  | CBasePager
setPages() | Sets the pagination information used by this pager. | CBasePager
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
createPageUrl() | Creates the URL suitable for pagination. | CBasePager
createPages() | Creates the default pagination. | CBasePager

Property Details

currentPage property
public integer getCurrentPage(boolean $recalculate=true)
public void setCurrentPage(integer $value)

the zero-based index of the current page. Defaults to 0.

See Also

  • CPagination::getCurrentPage
itemCount property
public integer getItemCount()
public void setItemCount(integer $value)

total number of items.

See Also

  • CPagination::getItemCount
pageCount property read-only
public integer getPageCount()

number of pages

See Also

  • CPagination::getPageCount
pageSize property
public integer getPageSize()
public void setPageSize(integer $value)

number of items in each page.

See Also

  • CPagination::getPageSize
pages property
public CPagination getPages()
public void setPages(CPagination $pages)

Returns the pagination information used by this pager.

Method Details

createPageUrl() method
protected string createPageUrl(integer $page)
$page | integer | the page that the URL should point to.
{return} | string | the created URL

Creates the URL suitable for pagination.

See Also

  • CPagination::createPageUrl
createPages() method
protected CPagination createPages()
{return} CPagination the default pagination instance.

Creates the default pagination. This is called by getPages when the pagination is not set before.

getCurrentPage() method
public integer getCurrentPage(boolean $recalculate=true)
$recalculate | boolean | whether to recalculate the current page based on the page size and item count.
{return} | integer | the zero-based index of the current page. Defaults to 0.

See Also

  • CPagination::getCurrentPage
getItemCount() method
public integer getItemCount()
{return} integer total number of items.

See Also

  • CPagination::getItemCount
getPageCount() method
public integer getPageCount()
{return} integer number of pages

See Also

  • CPagination::getPageCount
getPageSize() method
public integer getPageSize()
{return} integer number of items in each page.

See Also

  • CPagination::getPageSize
getPages() method
public CPagination getPages()
{return} CPagination the pagination information

Returns the pagination information used by this pager.

setCurrentPage() method
public void setCurrentPage(integer $value)
$value integer the zero-based index of the current page.

See Also

  • CPagination::setCurrentPage
setItemCount() method
public void setItemCount(integer $value)
$value integer total number of items.

See Also

  • CPagination::setItemCount
setPageSize() method
public void setPageSize(integer $value)
$value integer number of items in each page

See Also

  • CPagination::setPageSize
setPages() method
public void setPages(CPagination $pages)
$pages CPagination the pagination information

Sets the pagination information used by this pager.


CLinkPager

Package | system.web.widgets.pagers
Inheritance | class CLinkPager » CBasePager » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CLinkPager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CLinkPager displays a list of hyperlinks that lead to different pages of target.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the CSS file used for the widget. | CLinkPager
currentPage | integer | the zero-based index of the current page. | CBasePager
firstPageLabel | string | the text label for the first page button. | CLinkPager
footer | string | the text shown after page buttons. | CLinkPager
header | string | the text shown before page buttons. | CLinkPager
htmlOptions | array | HTML attributes for the pager container tag. | CLinkPager
id | string | id of the widget. | CWidget
itemCount | integer | total number of items. | CBasePager
lastPageLabel | string | the text label for the last page button. | CLinkPager
maxButtonCount | integer | maximum number of page buttons that can be displayed. | CLinkPager
nextPageLabel | string | the text label for the next page button. | CLinkPager
owner | CBaseController | owner/creator of this widget. | CWidget
pageCount | integer | number of pages | CBasePager
pageSize | integer | number of items in each page. | CBasePager
pages | CPagination | Returns the pagination information used by this pager. | CBasePager
prevPageLabel | string | the text label for the previous page button. | CLinkPager
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
pageRange | array | the begin and end pages that need to be displayed. | CLinkPager

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getCurrentPage() |  | CBasePager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getItemCount() |  | CBasePager
getOwner() |  | CWidget
getPageCount() |  | CBasePager
getPageSize() |  | CBasePager
getPages() | Returns the pagination information used by this pager. | CBasePager
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the pager by setting some default property values. | CLinkPager
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers the needed client scripts (mainly CSS file). | CLinkPager
registerCssFile() | Registers the needed CSS file. | CLinkPager
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CLinkPager
setCurrentPage() |  | CBasePager
setId() |  | CWidget
setItemCount() |  | CBasePager
setPageSize() |  | CBasePager
setPages() | Sets the pagination information used by this pager. | CBasePager
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
createPageButton() | Creates a page button. | CLinkPager
createPageButtons() | Creates the page buttons. | CLinkPager
createPageUrl() | Creates the URL suitable for pagination. | CBasePager
createPages() | Creates the default pagination. | CBasePager
getPageRange() |  | CLinkPager

Property Details

cssFile property
public mixed $cssFile;

the CSS file used for the widget. Defaults to null, meaning using the default CSS file included together with the widget. If false, no CSS file will be used. Otherwise, the specified CSS file will be included when using this widget.

firstPageLabel property
public string $firstPageLabel;

the text label for the first page button. Defaults to '<< First'.

footer property
public string $footer;

the text shown after page buttons.

header property
public string $header;

the text shown before page buttons. Defaults to 'Go to page: '.

htmlOptions property
public array $htmlOptions;

HTML attributes for the pager container tag.

lastPageLabel property
public string $lastPageLabel;

the text label for the last page button. Defaults to 'Last >>'.

maxButtonCount property
public integer $maxButtonCount;

maximum number of page buttons that can be displayed. Defaults to 10.

nextPageLabel property
public string $nextPageLabel;

the text label for the next page button. Defaults to 'Next >'.

pageRange property read-only
protected array getPageRange()

the begin and end pages that need to be displayed.

prevPageLabel property
public string $prevPageLabel;

the text label for the previous page button. Defaults to '< Previous'.

Method Details

createPageButton() method
protected string createPageButton(string $label, integer $page, string $class, boolean $hidden, boolean $selected)
$label | string | the text label for the button
$page | integer | the page number
$class | string | the CSS class for the page button. This could be 'page', 'first', 'last', 'next' or 'previous'.
$hidden | boolean | whether this page button is visible
$selected | boolean | whether this page button is selected
{return} | string | the generated button

Creates a page button. You may override this method to customize the page buttons.

createPageButtons() method
protected array createPageButtons()
{return} array a list of page buttons (in HTML code).

Creates the page buttons.

getPageRange() method
protected array getPageRange()
{return} array the begin and end pages that need to be displayed.

init() method
public void init()

Initializes the pager by setting some default property values.

registerClientScript() method
public void registerClientScript()

Registers the needed client scripts (mainly CSS file).

registerCssFile() method (available since v1.0.2)
public static void registerCssFile(string $url=NULL)
$url string the CSS URL. If null, a default CSS URL will be used.

Registers the needed CSS file.

run() method
public void run()

Executes the widget. This overrides the parent implementation by displaying the generated page buttons.


CListPager

Package | system.web.widgets.pagers
Inheritance | class CListPager » CBasePager » CWidget » CBaseController » CComponent
Since | 1.0
Version | $Id: CListPager.php 1678 2010-01-07 21:02:00Z qiang.xue $
CListPager displays a dropdown list that contains options leading to different pages of target.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
currentPage | integer | the zero-based index of the current page. | CBasePager
footer | string | the text shown after page buttons. | CListPager
header | string | the text shown before page buttons. | CListPager
htmlOptions | array | HTML attributes for the enclosing 'div' tag. | CListPager
id | string | id of the widget. | CWidget
itemCount | integer | total number of items. | CBasePager
owner | CBaseController | owner/creator of this widget. | CWidget
pageCount | integer | number of pages | CBasePager
pageSize | integer | number of items in each page. | CBasePager
pageTextFormat | string | the format string used to generate page selection text. | CListPager
pages | CPagination | Returns the pagination information used by this pager. | CBasePager
promptText | string | the text displayed as a prompt option in the dropdown list. | CListPager
skin | mixed | the name of the skin to be used by this widget. | CWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getCurrentPage() |  | CBasePager
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getItemCount() |  | CBasePager
getOwner() |  | CWidget
getPageCount() |  | CBasePager
getPageSize() |  | CBasePager
getPages() | Returns the pagination information used by this pager. | CBasePager
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the pager by setting some default property values. | CListPager
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CListPager
setCurrentPage() |  | CBasePager
setId() |  | CWidget
setItemCount() |  | CBasePager
setPageSize() |  | CBasePager
setPages() | Sets the pagination information used by this pager. | CBasePager
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
createPageUrl() | Creates the URL suitable for pagination. | CBasePager
createPages() | Creates the default pagination. | CBasePager
generatePageText() | Generates the list option for the specified page number. | CListPager

Property Details

footer property
public string $footer;

the text shown after page buttons.

header property
public string $header;

the text shown before page buttons. Defaults to 'Go to page: '.

htmlOptions property
public array $htmlOptions;

HTML attributes for the enclosing 'div' tag.

pageTextFormat property
public string $pageTextFormat;

the format string used to generate page selection text. The sprintf function will be used to perform the formatting.

promptText property
public string $promptText;

the text displayed as a prompt option in the dropdown list. Defaults to null, meaning no prompt.

Method Details

generatePageText() method
protected string generatePageText(integer $page)
$page | integer | zero-based page number
{return} | string | the list option for the page number

Generates the list option for the specified page number. You may override this method to customize the option display.

init() method
public void init()

Initializes the pager by setting some default property values.

run() method
public void run()

Executes the widget. This overrides the parent implementation by displaying the generated page buttons.


CTimestampBehavior

Package | zii.behaviors
Inheritance | class CTimestampBehavior » CActiveRecordBehavior » CModelBehavior » CBehavior » CComponent
Implements | IBehavior
Since | 1.1
Version | $Id: CTimestampBehavior.php 99 2010-01-07 20:55:13Z qiang.xue $
CTimestampBehavior will automatically fill date and time related atributes.

CTimestampBehavior will automatically fill date and time related atributes when the active record is created and/or upadated. You may specify an active record model to use this behavior like so:
public function behaviors(){
    return array(
        'CTimestampBehavior' => array(
            'class' => 'zii.behaviors.CTimestampBehavior',
            'createAttribute' => 'create_time_attribute',
            'updateAttribute' => 'update_time_attribute',
        )
    );
}
The createAttribute and updateAttribute options actually default to 'create_time' and 'update_time' respectively, so it is not required that you configure them. If you do not wish CTimestampBehavior to set a timestamp for record update or creation, set the corrisponding attribute option to null.

By default, the update attribute is only set on record update. If you also wish it to be set on record creation, set the setUpdateOnCreate option to true.

Although CTimestampBehavior attempts to figure out on it's own what value to inject into the timestamp attribute, you may specify a custom value to use instead via timestampExpression

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
createAttribute | mixed | The name of the attribute to store the creation time. | CTimestampBehavior
enabled | boolean | whether this behavior is enabled | CBehavior
owner | CComponent | the owner component that this behavior is attached to. | CBehavior
setUpdateOnCreate | bool | Whether to set the update attribute to the creation timestamp upon creation. | CTimestampBehavior
timestampExpression | mixed | The expression to use to generate the timestamp. | CTimestampBehavior
updateAttribute | mixed | The name of the attribute to store the modification time. | CTimestampBehavior

Protected Properties

Hide inherited properties

Property | Type | Description | Defined By
map | array | Maps column types to database method | CTimestampBehavior

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
afterConstruct() | Responds to CActiveRecord::onAfterConstruct event. | CActiveRecordBehavior
afterDelete() | Responds to CActiveRecord::onAfterDelete event. | CActiveRecordBehavior
afterFind() | Responds to CActiveRecord::onAfterFind event. | CActiveRecordBehavior
afterSave() | Responds to CActiveRecord::onAfterSave event. | CActiveRecordBehavior
afterValidate() | Responds to CModel::onAfterValidate event. | CModelBehavior
asa() | Returns the named behavior object. | CComponent
attach() | Attaches the behavior object to the component. | CBehavior
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beforeDelete() | Responds to CActiveRecord::onBeforeDelete event. | CActiveRecordBehavior
beforeFind() | Responds to CActiveRecord::onBeforeFind event. | CActiveRecordBehavior
beforeSave() | Responds to CModel::onBeforeSave event. | CTimestampBehavior
beforeValidate() | Responds to CModel::onBeforeValidate event. | CModelBehavior
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detach() | Detaches the behavior object from the component. | CBehavior
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
events() | Declares events and the corresponding event handler methods. | CActiveRecordBehavior
getEnabled() |  | CBehavior
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getOwner() |  | CBehavior
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
raiseEvent() | Raises an event. | CComponent
setEnabled() |  | CBehavior

Protected Methods

Hide inherited methods

Method | Description | Defined By
getTimestampByAttribute() | Gets the approprate timestamp depending on the column type $attribute is | CTimestampBehavior
getTimestampByColumnType() | Returns the approprate timestamp depending on $columnType | CTimestampBehavior

Property Details

createAttribute property
public mixed $createAttribute;

The name of the attribute to store the creation time. Set to null to not use a timstamp for the creation attribute. Defaults to 'create_time'

map property
protected static array $map;

Maps column types to database method

setUpdateOnCreate property
public bool $setUpdateOnCreate;

Whether to set the update attribute to the creation timestamp upon creation. Otherwise it will be left alone. Defaults to false.

timestampExpression property
public mixed $timestampExpression;

The expression to use to generate the timestamp. e.g. 'time()'. Defaults to null meaning that we will attempt to figure out the appropriate timestamp automatically. If we fail at finding the appropriate timestamp, then it will fall back to using the current UNIX timestamp

updateAttribute property
public mixed $updateAttribute;

The name of the attribute to store the modification time. Set to null to not use a timstamp for the update attribute. Defaults to 'update_time'

Method Details

beforeSave() method
public void beforeSave(CModelEvent $event)
$event CModelEvent event parameter

Responds to CModel::onBeforeSave event. Sets the values of the creation or modified attributes as configured

getTimestampByAttribute() method
protected mixed getTimestampByAttribute(string $attribute)
$attribute | string | $attribute
{return} | mixed | timestamp (eg unix timestamp or a mysql function)

Gets the approprate timestamp depending on the column type $attribute is

getTimestampByColumnType() method
protected mixed getTimestampByColumnType(string $columnType)
$columnType | string | $columnType
{return} | mixed | timestamp (eg unix timestamp or a mysql function)

Returns the approprate timestamp depending on $columnType


CBaseListView

Package | zii.widgets
Inheritance | abstract class CBaseListView » CWidget » CBaseController » CComponent
Subclasses | CGridView, CListView
Since | 1.1
Version | $Id: CBaseListView.php 118 2010-01-21 17:42:01Z qiang.xue $
CBaseListView is the base class for CListView and CGridView.

CBaseListView implements the common features needed by a view wiget for rendering multiple models.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
dataProvider | IDataProvider | the data provider for the view. | CBaseListView
emptyText | string | the message to be displayed when dataProvider does not have any data. | CBaseListView
enablePagination | boolean | whether to enable pagination. | CBaseListView
enableSorting | boolean | whether to enable sorting. | CBaseListView
htmlOptions | array | the HTML options for the view container tag. | CBaseListView
id | string | id of the widget. | CWidget
itemsCssClass | string | the CSS class name for the container of all data item display. | CBaseListView
loadingCssClass | string | the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. | CBaseListView
owner | CBaseController | owner/creator of this widget. | CWidget
pager | array | the configuration for the pager. | CBaseListView
pagerCssClass | string | the CSS class name for the pager container. | CBaseListView
skin | mixed | the name of the skin to be used by this widget. | CWidget
summaryCssClass | string | the CSS class name for the summary text container. | CBaseListView
summaryText | string | the summary text template for the view. | CBaseListView
tagName | string | the tag name for the view container. | CBaseListView
template | string | the template to be used to control the layout of various sections in the view. | CBaseListView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the view. | CBaseListView
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers necessary client scripts. | CBaseListView
render() | Renders a view. | CWidget
renderContent() | Renders the main content of the view. | CBaseListView
renderEmptyText() | Renders the empty message when there is no data. | CBaseListView
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
renderItems() | Renders the data items for the view. | CBaseListView
renderKeys() | Renders the key values of the data in a hidden tag. | CBaseListView
renderPager() | Renders the pager. | CBaseListView
renderSummary() | Renders the summary text. | CBaseListView
run() | Renders the view. | CBaseListView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderSection() | Renders a section. | CBaseListView

Property Details

dataProvider property
public IDataProvider $dataProvider;

the data provider for the view.

emptyText property
public string $emptyText;

the message to be displayed when dataProvider does not have any data.

enablePagination property
public boolean $enablePagination;

whether to enable pagination. Note that if the IDataProvider::pagination property of dataProvider is false, this will be treated as false as well. When pagination is enabled, a pager will be displayed in the view so that it can trigger pagination of the data display. Defaults to true.

enableSorting property
public boolean $enableSorting;

whether to enable sorting. Note that if the IDataProvider::sort property of dataProvider is false, this will be treated as false as well. When sorting is enabled, sortable columns will have their headers clickable to trigger sorting along that column. Defaults to true.

See Also

  • sortableAttributes
htmlOptions property
public array $htmlOptions;

the HTML options for the view container tag.

itemsCssClass property
public string $itemsCssClass;

the CSS class name for the container of all data item display. Defaults to 'items'.

loadingCssClass property (available since v1.1.1)
public string $loadingCssClass;

the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. Defaults to 'loading'.

pager property
public array $pager;

the configuration for the pager. Defaults to array('class'=>'CLinkPager').

See Also

  • enablePagination
pagerCssClass property
public string $pagerCssClass;

the CSS class name for the pager container. Defaults to 'pager'.

summaryCssClass property
public string $summaryCssClass;

the CSS class name for the summary text container. Defaults to 'summary'.

summaryText property
public string $summaryText;

the summary text template for the view. These tokens are recognized: {start}, {end} and {count}. They will be replaced with the starting row number, ending row number and total number of data records.

tagName property
public string $tagName;

the tag name for the view container. Defaults to 'div'.

template property
public string $template;

the template to be used to control the layout of various sections in the view. These tokens are recognized: {summary}, {items} and {pager}. They will be replaced with the summary text, the items, and the pager.

Method Details

init() method
public void init()

Initializes the view. This method will initialize required property values and instantiate columns objects.

registerClientScript() method
public void registerClientScript()

Registers necessary client scripts. This method is invoked by run. Child classes may override this method to register customized client scripts.

renderContent() method
public void renderContent()

Renders the main content of the view. The content is divided into sections, such as summary, items, pager. Each section is rendered by a method named as "renderXyz", where "Xyz" is the section name. The rendering results will replace the corresponding placeholders in template.

renderEmptyText() method
public void renderEmptyText()

Renders the empty message when there is no data.

renderItems() method
abstract public void renderItems()

Renders the data items for the view. Each item is corresponding to a single data model instance. Child classes should override this method to provide the actual item rendering logic.

renderKeys() method
public void renderKeys()

Renders the key values of the data in a hidden tag.

renderPager() method
public void renderPager()

Renders the pager.

renderSection() method
protected string renderSection(array $matches)
$matches | array | the matches, where $matches[0] represents the whole placeholder, while $matches[1] contains the name of the matched placeholder.
{return} | string | the rendering result of the section

Renders a section. This method is invoked by renderContent for every placeholder found in template. It should return the rendering result that would replace the placeholder.

renderSummary() method
public void renderSummary()

Renders the summary text.

run() method
public void run()

Renders the view. This is the main entry of the whole view rendering. Child classes should mainly override renderContent method.


CBreadcrumbs

Package | zii.widgets
Inheritance | class CBreadcrumbs » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CBreadcrumbs.php 99 2010-01-07 20:55:13Z qiang.xue $
CBreadcrumbs displays a list of links indicating the position of the current page in the whole website.

For example, breadcrumbs like "Home > Sample Post > Edit" means the user is viewing an edit page for the "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home" to return to the homepage.

To use CBreadcrumbs, one usually needs to configure its links property, which specifies the links to be displayed. For example,

$this->widget('zii.widgets.CBreadcrumbs', array(
    'links'=>array(
        'Sample post'=>array('post/view', 'id'=>12),
        'Edit',
    ),
));

Because breadcrumbs usually appears in nearly every page of a website, the widget is better to be placed in a layout view. One can define a property "breadcrumbs" in the base controller class and assign it to the widget in the layout, like the following:

$this->widget('zii.widgets.CBreadcrumbs', array(
    'links'=>$this->breadcrumbs,
));

Then, in each view script, one only needs to assign the "breadcrumbs" property as needed.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
encodeLabel | boolean | whether to HTML encode the link labels. | CBreadcrumbs
homeLink | string | the first hyperlink in the breadcrumbs (called home link). | CBreadcrumbs
htmlOptions | array | the HTML attributes for the breadcrumbs container tag. | CBreadcrumbs
id | string | id of the widget. | CWidget
links | array | list of hyperlinks to appear in the breadcrumbs. | CBreadcrumbs
owner | CBaseController | owner/creator of this widget. | CWidget
separator | string | the separator between links in the breadcrumbs. | CBreadcrumbs
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the tag name for the breadcrumbs container tag. | CBreadcrumbs
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the content of the portlet. | CBreadcrumbs
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

encodeLabel property
public boolean $encodeLabel;

whether to HTML encode the link labels. Defaults to true.

homeLink property
public string $homeLink;

the first hyperlink in the breadcrumbs (called home link). If this property is not set, it defaults to a link pointing to CWebApplication::homeUrl with label 'Home'. If this property is false, the home link will not be rendered.

htmlOptions property
public array $htmlOptions;

the HTML attributes for the breadcrumbs container tag.

links property
public array $links;

list of hyperlinks to appear in the breadcrumbs. If this property is empty, the widget will not render anything. Each key-value pair in the array will be used to generate a hyperlink by calling CHtml::link(key, value). For this reason, the key refers to the label of the link while the value can be a string or an array (used to create a URL). For more details, please refer to CHtml::link. If an element's key is an integer, it means the element will be rendered as a label only (meaning the current page).

The following example will generate breadcrumbs as "Home > Sample post > Edit", where "Home" points to the homepage, "Sample post" points to the "index.php?r=post/view&id=12" page, and "Edit" is a label. Note that the "Home" link is specified via homeLink separately.

array(
    'Sample post'=>array('post/view', 'id'=>12),
    'Edit',
)

separator property
public string $separator;

the separator between links in the breadcrumbs. Defaults to ' » '.

tagName property
public string $tagName;

the tag name for the breadcrumbs container tag. Defaults to 'div'.

Method Details

run() method
public void run()

Renders the content of the portlet.


CDetailView

Package | zii.widgets
Inheritance | class CDetailView » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CDetailView.php 138 2010-03-07 13:23:21Z qiang.xue $
CDetailView displays the detail of a single data model.

CDetailView is best used for displaying a model in a regular format (e.g. each model attribute is displayed as a row in a table.) The model can be either an instance of CModel or an associative array.

CDetailView uses the attributes property to determines which model attributes should be displayed and how they should be formatted.

A typical usage of CDetailView is as follows:
$this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        'title',             // title attribute (in plain text)
        'owner.name',        // an attribute of the related object "owner"
        'description:html',  // description attribute in HTML
        array(               // related city displayed as a link
            'label'=>'City',
            'type'=>'raw',
            'value'=>CHtml::link(CHtml::encode($model->city->name),
                                 array('city/view','id'=>$model->city->id)),
        ),
    ),
));

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attributes | array | a list of attributes to be displayed in the detail view. | CDetailView
baseScriptUrl | string | the base script URL for all detail view resources (e. | CDetailView
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | string | the URL of the CSS file used by this detail view. | CDetailView
data | mixed | the data model whose details are to be displayed. | CDetailView
formatter | CFormatter | the formatter instance. | CDetailView
htmlOptions | array | the HTML options used for tagName | CDetailView
id | string | id of the widget. | CWidget
itemCssClass | array | the CSS class names for the items displaying attribute values. | CDetailView
itemTemplate | string | the template used to render a single attribute. | CDetailView
nullDisplay | string | the text to be displayed when an attribute value is null. | CDetailView
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the tag for rendering the detail view. | CDetailView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getFormatter() |  | CDetailView
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the detail view. | CDetailView
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the detail view. | CDetailView
setFormatter() |  | CDetailView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Property Details

attributes property
public array $attributes;

a list of attributes to be displayed in the detail view. Each array element represents the specification for displaying one particular attribute.

An attribute can be specified as a string in the format of "Name:Type:Label". Both "Type" and "Label" are optional.

"Name" refers to the attribute name. It can be either a property (e.g. "title") or a sub-property (e.g. "owner.username").

"Label" represents the label for the attribute display. If it is not given, "Name" will be used to generate the appropriate label.

"Type" represents the type of the attribute. It determines how the attribute value should be formatted and displayed. It is defaulted to be 'text'. "Type" should be recognizable by the formatter. In particular, if "Type" is "xyz", then the "formatXyz" method of formatter will be invoked to format the attribute value for display. By default when CFormatter is used, these "Type" values are valid: raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url. For more details about these types, please refer to CFormatter.

An attribute can also be specified in terms of an array with the following elements:

  • label: the label associated with the attribute. If this is not specified, the following "name" element will be used to generate an appropriate label.
  • name: the name of the attribute. This can be either a property or a sub-property of the model. If the above "value" element is specified, this will be ignored.
  • value: the value to be displayed. If this is not specified, the following "name" element will be used to retrieve the corresponding attribute value for display. Note that this value will be formatted according to the "type" option as described below.
  • type: the type of the attribute that determines how the attribute value would be formatted. Please see above for possible values.
  • template: the template used to render the attribute. If this is not specified, itemTemplate will be used instead. For more details on how to set this option, please refer to itemTemplate. This option is available since version 1.1.1.

baseScriptUrl property
public string $baseScriptUrl;

the base script URL for all detail view resources (e.g. javascript, CSS file, images). Defaults to null, meaning using the integrated detail view resources (which are published as assets).

cssFile property
public string $cssFile;

the URL of the CSS file used by this detail view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

data property
public mixed $data;

the data model whose details are to be displayed. This can be either a CModel instance (e.g. a CActiveRecord object or a CFormModel object) or an associative array.

formatter property
public CFormatter getFormatter()
public void setFormatter(CFormatter $value)

the formatter instance. Defaults to the 'format' application component.

htmlOptions property
public array $htmlOptions;

the HTML options used for tagName

itemCssClass property
public array $itemCssClass;

the CSS class names for the items displaying attribute values. If multiple CSS class names are given, they will be assigned to the items sequentially and repeatedly. Defaults to array('odd', 'even').

itemTemplate property
public string $itemTemplate;

the template used to render a single attribute. Defaults to a table row. These tokens are recognized: "{class}", "{label}" and "{value}". They will be replaced with the CSS class name for the item, the label and the attribute value, respectively.

See Also

  • itemCssClass
nullDisplay property
public string $nullDisplay;

the text to be displayed when an attribute value is null. Defaults to "Not set".

tagName property
public string $tagName;

the name of the tag for rendering the detail view. Defaults to 'table'.

See Also

  • itemTemplate

Method Details

getFormatter() method
public CFormatter getFormatter()
{return} CFormatter the formatter instance. Defaults to the 'format' application component.

init() method
public void init()

Initializes the detail view. This method will initialize required property values.

run() method
public void run()

Renders the detail view. This is the main entry of the whole detail view rendering.

setFormatter() method
public void setFormatter(CFormatter $value)
$value CFormatter the formatter instance


CListView

Package | zii.widgets
Inheritance | class CListView » CBaseListView » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CListView.php 123 2010-02-02 21:09:35Z qiang.xue $
CListView displays a list of data items in terms of a list.

Unlike CGridView which displays the data items in a table, CListView allows one to use a view template to render each data item. As a result, CListView could generate more flexible rendering result.

CListView supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode or normal page request. A benefit of using CListView is that when the user browser disables JavaScript, the sorting and pagination automatically degenerate to normal page requests and are still functioning as expected.

CListView should be used together with a data provider, preferrably a CActiveDataProvider.

The minimal code needed to use CListView is as follows:

$dataProvider=new CActiveDataProvider('Post');

$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_post',   // refers to the partial view named '_post'
    'sortableAttributes'=>array(
        'title',
        'create_time'=>'Post Time',
    ),
));

The above code first creates a data provider for the Post ActiveRecord class. It then uses CListView to display every data item as returned by the data provider. The display is done via the partial view named '_post'. This partial view will be rendered once for every data item. In the view, one can access the current data item via variable $data. For more details, see itemView.

In order to support sorting, one has to specify the sortableAttributes property. By doing so, a list of hyperlinks that can sort the data will be displayed.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
afterAjaxUpdate | string | a javascript function that will be invoked after a successful AJAX response is received. | CListView
ajaxUpdate | mixed | the ID of the container whose content may be updated with an AJAX response. | CListView
ajaxVar | string | the name of the GET variable that indicates the request is an AJAX request triggered by this widget. | CListView
baseScriptUrl | string | the base script URL for all list view resources (e. | CListView
beforeAjaxUpdate | string | a javascript function that will be invoked before an AJAX update occurs. | CListView
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | string | the URL of the CSS file used by this list view. | CListView
dataProvider | IDataProvider | the data provider for the view. | CBaseListView
emptyText | string | the message to be displayed when dataProvider does not have any data. | CBaseListView
enablePagination | boolean | whether to enable pagination. | CBaseListView
enableSorting | boolean | whether to enable sorting. | CBaseListView
htmlOptions | array | the HTML options for the view container tag. | CBaseListView
id | string | id of the widget. | CWidget
itemView | string | the view used for rendering each data item. | CListView
itemsCssClass | string | the CSS class name for the container of all data item display. | CBaseListView
loadingCssClass | string | the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. | CBaseListView
owner | CBaseController | owner/creator of this widget. | CWidget
pager | array | the configuration for the pager. | CBaseListView
pagerCssClass | string | the CSS class name for the pager container. | CBaseListView
skin | mixed | the name of the skin to be used by this widget. | CWidget
sortableAttributes | array | list of sortable attribute names. | CListView
sorterCssClass | string | the CSS class name for the sorter container. | CListView
sorterFooter | string | the text shown after sort links. | CListView
sorterHeader | string | the text shown before sort links. | CListView
summaryCssClass | string | the CSS class name for the summary text container. | CBaseListView
summaryText | string | the summary text template for the view. | CBaseListView
tagName | string | the tag name for the view container. | CBaseListView
template | string | the template to be used to control the layout of various components in the list view. | CBaseListView
viewData | array | additional data to be passed to itemView when rendering each data item. | CListView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the list view. | CListView
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers necessary client scripts. | CListView
render() | Renders a view. | CWidget
renderContent() | Renders the main content of the view. | CBaseListView
renderEmptyText() | Renders the empty message when there is no data. | CBaseListView
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
renderItems() | Renders the data item list. | CListView
renderKeys() | Renders the key values of the data in a hidden tag. | CBaseListView
renderPager() | Renders the pager. | CBaseListView
renderSorter() | Renders the sorter. | CListView
renderSummary() | Renders the summary text. | CBaseListView
run() | Renders the view. | CBaseListView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderSection() | Renders a section. | CBaseListView

Property Details

afterAjaxUpdate property
public string $afterAjaxUpdate;

a javascript function that will be invoked after a successful AJAX response is received. The function signature is function(id, data) where 'id' refers to the ID of the list view 'data' the received ajax response data.

ajaxUpdate property
public mixed $ajaxUpdate;

the ID of the container whose content may be updated with an AJAX response. Defaults to null, meaning the container for this list view instance. If it is set false, it means sorting and pagination will be performed in normal page requests instead of AJAX requests. If the sorting and pagination should trigger the update of multiple containers' content in AJAX fashion, these container IDs may be listed here (separated with comma).

ajaxVar property
public string $ajaxVar;

the name of the GET variable that indicates the request is an AJAX request triggered by this widget. Defaults to 'ajax'. This is effective only when ajaxUpdate is not false.

baseScriptUrl property
public string $baseScriptUrl;

the base script URL for all list view resources (e.g. javascript, CSS file, images). Defaults to null, meaning using the integrated list view resources (which are published as assets).

beforeAjaxUpdate property
public string $beforeAjaxUpdate;

a javascript function that will be invoked before an AJAX update occurs. The function signature is function(id) where 'id' refers to the ID of the list view.

cssFile property
public string $cssFile;

the URL of the CSS file used by this list view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

itemView property
public string $itemView;

the view used for rendering each data item. This property value will be passed as the first parameter to either CController::renderPartial or CWidget::render to render each data item. In the corresponding view template, the following variables can be used in addition to those declared in viewData:

  • $this: refers to the owner of this list view widget. For example, if the widget is in the view of a controller, then $this refers to the controller.
  • $data: refers to the data item currently being rendered.
  • $index: refers to the zero-based index of the data item currently being rendered.
  • $widget: refers to this list view widget instance.

sortableAttributes property
public array $sortableAttributes;

list of sortable attribute names. In order for an attribute to be sortable, it must also appear as as a sortable attribute the IDataProvider::sort property of dataProvider.

See Also

  • enableSorting
sorterCssClass property
public string $sorterCssClass;

the CSS class name for the sorter container. Defaults to 'sorter'.

sorterFooter property
public string $sorterFooter;

the text shown after sort links. Defaults to empty.

sorterHeader property
public string $sorterHeader;

the text shown before sort links. Defaults to 'Sort by: '.

viewData property
public array $viewData;

additional data to be passed to itemView when rendering each data item. This array will be extracted into local PHP variables that can be accessed in the itemView.

Method Details

init() method
public void init()

Initializes the list view. This method will initialize required property values and instantiate columns objects.

registerClientScript() method
public void registerClientScript()

Registers necessary client scripts.

renderItems() method
public void renderItems()

Renders the data item list.

renderSorter() method
public void renderSorter()

Renders the sorter.


CMenu

Package | zii.widgets
Inheritance | class CMenu » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CMenu.php 140 2010-03-10 20:03:07Z qiang.xue $
CMenu displays a multi-level menu using nested HTML lists.

The main property of CMenu is items, which specifies the possible items in the menu. A menu item has three main properties: visible, active and items. The "visible" property specifies whether the menu item is currently visible. The "active" property specifies whether the menu item is currently selected. And the "items" property specifies the child menu items.

The following example shows how to use CMenu:
$this->widget('zii.widgets.CMenu', array(
    'items'=>array(
        array('label'=>'Home', 'url'=>array('site/index')),
        array('label'=>'Products', 'url'=>array('product/index'), 'items'=>array(
            array('label'=>'New Arrivals', 'url'=>array('product/new', 'tag'=>'new')),
            array('label'=>'Most Popular', 'url'=>array('product/index', 'tag'=>'popular')),
        )),
        array('label'=>'Login', 'url'=>array('site/login'), 'visible'=>Yii::app()->user->isGuest),
    ),
));

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
activateParents | boolean | whether to activate parent menu items when one of the corresponding child menu items is active. | CMenu
activeCssClass | string | the CSS class to be appended to the active menu item. | CMenu
controller | CController | the controller that this widget belongs to. | CWidget
encodeLabel | boolean | whether the labels for menu items should be HTML-encoded. | CMenu
hideEmptyItems | boolean | whether to hide empty menu items. | CMenu
htmlOptions | array | HTML attributes for the menu's root container tag | CMenu
id | string | id of the widget. | CWidget
itemTemplate | string | the template used to render an individual menu item. | CMenu
items | array | list of menu items. | CMenu
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
submenuHtmlOptions | array | HTML attributes for the submenu's container tag. | CMenu
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the menu widget. | CMenu
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Calls renderMenu to render the menu. | CMenu
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
isItemActive() | Checks whether a menu item is active. | CMenu
normalizeItems() | Normalizes the items property so that the 'active' state is properly identified for every menu item. | CMenu
renderMenu() | Renders the menu items. | CMenu
renderMenuRecursive() | Recursively renders the menu items. | CMenu

Property Details

activateParents property
public boolean $activateParents;

whether to activate parent menu items when one of the corresponding child menu items is active. The activated parent menu items will also have its CSS classes appended with activeCssClass. Defaults to false.

activeCssClass property
public string $activeCssClass;

the CSS class to be appended to the active menu item. Defaults to 'active'. If empty, the CSS class of menu items will not be changed.

encodeLabel property
public boolean $encodeLabel;

whether the labels for menu items should be HTML-encoded. Defaults to true.

hideEmptyItems property
public boolean $hideEmptyItems;

whether to hide empty menu items. An empty menu item is one whose 'url' option is not set and which doesn't contain visible child menu items. Defaults to true.

htmlOptions property
public array $htmlOptions;

HTML attributes for the menu's root container tag

itemTemplate property (available since v1.1.1)
public string $itemTemplate;

the template used to render an individual menu item. In this template, the token "{menu}" will be replaced with the corresponding menu link or text. If this property is not set, each menu will be rendered without any decoration. This property will be overridden by the 'template' option set in individual menu items via {@items}.

items property
public array $items;

list of menu items. Each menu item is specified as an array of name-value pairs. Possible option names include the following:

  • label: string, required, specifies the menu item label. When encodeLabel is true, the label will be HTML-encoded.
  • url: string or array, optional, specifies the URL of the menu item. It is passed to CHtml::normalizeUrl to generate a valid URL. If this is not set, the menu item will be rendered as a span text.
  • visible: boolean, optional, whether this menu item is visible. Defaults to true. This can be used to control the visibility of menu items based on user permissions.
  • items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.
  • active: boolean, optional, whether this menu item is in active state (currently selected). If a menu item is active and activeClass is not empty, its CSS class will be appended with activeClass. If this option is not set, the menu item will be set active automatically when the current request is triggered by url.
  • template: string, optional, the template used to render this menu item. In this template, the token "{menu}" will be replaced with the corresponding menu link or text. Please see itemTemplate for more details. This option has been available since version 1.1.1.
  • linkOptions: array, optional, additional HTML attributes to be rendered for the link or span tag of the menu item.
  • itemOptions: array, optional, additional HTML attributes to be rendered for the container tag of the menu item.

submenuHtmlOptions property
public array $submenuHtmlOptions;

HTML attributes for the submenu's container tag.

Method Details

init() method
public void init()

Initializes the menu widget. This method mainly normalizes the items property. If this method is overridden, make sure the parent implementation is invoked.

isItemActive() method
protected boolean isItemActive(array $item, string $route)
$item | array | the menu item to be checked
$route | string | the route of the current request
{return} | boolean | whether the menu item is active

Checks whether a menu item is active. This is done by checking if the currently requested URL is generated by the 'url' option of the menu item.

normalizeItems() method
protected array normalizeItems(array $items, string $route, boolean $active)
$items | array | the items to be normalized.
$route | string | the route of the current request.
$active | boolean | whether there is an active child menu item.
{return} | array | the normalized menu items

Normalizes the items property so that the 'active' state is properly identified for every menu item.

renderMenu() method
protected void renderMenu(array $items)
$items array menu items. Each menu item will be an array with at least two elements: 'label' and 'active'. It may have three other optional elements: 'items', 'linkOptions' and 'itemOptions'.

Renders the menu items.

renderMenuRecursive() method
protected void renderMenuRecursive(array $items)
$items array the menu items to be rendered recursively

Recursively renders the menu items.

run() method
public void run()

Calls renderMenu to render the menu.


CPortlet

Package | zii.widgets
Inheritance | class CPortlet » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CPortlet.php 104 2010-01-09 20:46:58Z qiang.xue $
CPortlet is the base class for portlet widgets.

A portlet displays a fragment of content, usually in terms of a block on the side bars of a Web page.

To specify the content of the portlet, override the renderContent method, or insert the content code between the CController::beginWidget and CController::endWidget calls. For example,

<?php $this->beginWidget('zii.widgets.CPortlet'); ?>
    ...insert content here...
<?php $this->endWidget(); ?>

A portlet also has an optional title. One may also override renderDecoration to further customize the decorative display of a portlet (e.g. adding min/max buttons).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
contentCssClass | string | the CSS class for the content container tag. | CPortlet
controller | CController | the controller that this widget belongs to. | CWidget
decorationCssClass | string | the CSS class for the decoration container tag. | CPortlet
htmlOptions | array | the HTML attributes for the portlet container tag. | CPortlet
id | string | id of the widget. | CWidget
owner | CBaseController | owner/creator of this widget. | CWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the tag name for the portlet container tag. | CPortlet
title | string | the title of the portlet. | CPortlet
titleCssClass | string | the CSS class for the portlet title tag. | CPortlet
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CPortlet
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the content of the portlet. | CPortlet
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderContent() | Renders the content of the portlet. | CPortlet
renderDecoration() | Renders the decoration for the portlet. | CPortlet

Property Details

contentCssClass property
public string $contentCssClass;

the CSS class for the content container tag. Defaults to 'portlet-content'.

decorationCssClass property
public string $decorationCssClass;

the CSS class for the decoration container tag. Defaults to 'portlet-decoration'.

htmlOptions property
public array $htmlOptions;

the HTML attributes for the portlet container tag.

tagName property
public string $tagName;

the tag name for the portlet container tag. Defaults to 'div'.

title property
public string $title;

the title of the portlet. Defaults to null. When this is not set, Decoration will not be displayed. Note that the title will not be HTML-encoded when rendering.

titleCssClass property
public string $titleCssClass;

the CSS class for the portlet title tag. Defaults to 'portlet-title'.

Method Details

init() method
public void init()

Initializes the widget. This renders the open tags needed by the portlet. It also renders the decoration, if any.

renderContent() method
protected void renderContent()

Renders the content of the portlet. Child classes should override this method to render the actual content.

renderDecoration() method
protected void renderDecoration()

Renders the decoration for the portlet. The default implementation will render the title if it is set.

run() method
public void run()

Renders the content of the portlet.


CButtonColumn

Package | zii.widgets.grid
Inheritance | class CButtonColumn » CGridColumn » CComponent
Since | 1.1
Version | $Id: CButtonColumn.php 142 2010-03-10 20:53:52Z qiang.xue $
CButtonColumn represents a grid view column that renders one or several buttons.

By default, it will display three buttons, "view", "update" and "delete", which triggers the corresponding actions on the model of the row.

By configuring buttons and template properties, the column can display other buttons and customize the display order of the buttons.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
buttons | array | the configuration for additional buttons. | CButtonColumn
cssClassExpression | string | a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. | CGridColumn
deleteButtonImageUrl | string | the image URL for the delete button. | CButtonColumn
deleteButtonLabel | string | the label for the delete button. | CButtonColumn
deleteButtonOptions | array | the HTML options for the view button tag. | CButtonColumn
deleteButtonUrl | string | a PHP expression that is evaluated for every delete button and whose result is used as the URL for the delete button. | CButtonColumn
deleteConfirmation | string | the confirmation message to be displayed when delete button is clicked. | CButtonColumn
footer | string | the footer cell text. | CGridColumn
footerHtmlOptions | array | the HTML options for the footer cell tag. | CGridColumn
grid | CGridView | the grid view object that owns this column. | CGridColumn
hasFooter | boolean | whether this column has a footer cell. | CGridColumn
header | string | the header cell text. | CGridColumn
headerHtmlOptions | array | the HTML options for the header cell tag. | CGridColumn
htmlOptions | array | the HTML options for the data cell tags. | CGridColumn
id | string | the ID of this column. | CGridColumn
template | string | the template that is used to render the content in each data cell. | CButtonColumn
updateButtonImageUrl | string | the image URL for the update button. | CButtonColumn
updateButtonLabel | string | the label for the update button. | CButtonColumn
updateButtonOptions | array | the HTML options for the update button tag. | CButtonColumn
updateButtonUrl | string | a PHP expression that is evaluated for every update button and whose result is used as the URL for the update button. | CButtonColumn
viewButtonImageUrl | string | the image URL for the view button. | CButtonColumn
viewButtonLabel | string | the label for the view button. | CButtonColumn
viewButtonOptions | array | the HTML options for the view button tag. | CButtonColumn
viewButtonUrl | string | a PHP expression that is evaluated for every view button and whose result is used as the URL for the view button. | CButtonColumn
visible | boolean | whether this column is visible. | CGridColumn

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGridColumn
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasFooter() |  | CGridColumn
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column. | CButtonColumn
raiseEvent() | Raises an event. | CComponent
renderDataCell() | Renders a data cell. | CGridColumn
renderFilterCell() | Renders the filter cell. | CGridColumn
renderFooterCell() | Renders the footer cell. | CGridColumn
renderHeaderCell() | Renders the header cell. | CGridColumn

Protected Methods

Hide inherited methods

Method | Description | Defined By
initDefaultButtons() | Initializes the default buttons (view, update and delete). | CButtonColumn
registerClientScript() | Registers the client scripts for the button column. | CButtonColumn
renderButton() | Renders a link button. | CButtonColumn
renderDataCellContent() | Renders the data cell content. | CButtonColumn
renderFilterCellContent() | Renders the filter cell content. | CGridColumn
renderFooterCellContent() | Renders the footer cell content. | CGridColumn
renderHeaderCellContent() | Renders the header cell content. | CGridColumn

Property Details

buttons property
public array $buttons;

the configuration for additional buttons. Each array element specifies a single button which has the following format:

'buttonID' => array(
    'label'=>'...',     // text label of the button
    'url'=>'...',       // a PHP expression for generating the URL of the button
    'imageUrl'=>'...',  // image URL of the button. If not set or false, a text link is used
    'options'=>array(...), // HTML options for the button tag
    'click'=>'...',     // a JS function to be invoked when the button is clicked
    'visible'=>'...',   // a PHP expression for determining whether the button is visible
)
In the PHP expression for the 'url' option and/or 'visible' option, the variable $row refers to the current row number (zero-based), and $data refers to the data model for the row.

Note that in order to display these additional buttons, the template property needs to be configured so that the corresponding button IDs appear as tokens in the template.

deleteButtonImageUrl property
public string $deleteButtonImageUrl;

the image URL for the delete button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

deleteButtonLabel property
public string $deleteButtonLabel;

the label for the delete button. Defaults to "Delete". Note that the label will not be HTML-encoded when rendering.

deleteButtonOptions property
public array $deleteButtonOptions;

the HTML options for the view button tag.

deleteButtonUrl property
public string $deleteButtonUrl;

a PHP expression that is evaluated for every delete button and whose result is used as the URL for the delete button. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

deleteConfirmation property
public string $deleteConfirmation;

the confirmation message to be displayed when delete button is clicked. By setting this property to be false, no confirmation message will be displayed.

template property
public string $template;

the template that is used to render the content in each data cell. These default tokens are recognized: {view}, {update} and {delete}. If the buttons property defines additional buttons, their IDs are also recognized here. For example, if a button named 'preview' is declared in buttons, we can use the token '{preview}' here to specify where to display the button.

updateButtonImageUrl property
public string $updateButtonImageUrl;

the image URL for the update button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

updateButtonLabel property
public string $updateButtonLabel;

the label for the update button. Defaults to "Update". Note that the label will not be HTML-encoded when rendering.

updateButtonOptions property
public array $updateButtonOptions;

the HTML options for the update button tag.

updateButtonUrl property
public string $updateButtonUrl;

a PHP expression that is evaluated for every update button and whose result is used as the URL for the update button. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

viewButtonImageUrl property
public string $viewButtonImageUrl;

the image URL for the view button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

viewButtonLabel property
public string $viewButtonLabel;

the label for the view button. Defaults to "View". Note that the label will not be HTML-encoded when rendering.

viewButtonOptions property
public array $viewButtonOptions;

the HTML options for the view button tag.

viewButtonUrl property
public string $viewButtonUrl;

a PHP expression that is evaluated for every view button and whose result is used as the URL for the view button. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

Method Details

init() method
public void init()

Initializes the column. This method registers necessary client script for the button column.

initDefaultButtons() method
protected void initDefaultButtons()

Initializes the default buttons (view, update and delete).

registerClientScript() method
protected void registerClientScript()

Registers the client scripts for the button column.

renderButton() method
protected void renderButton(string $id, array $button, integer $row, mixed $data)
$id | string | the ID of the button
$button | array | the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements. See buttons for more details.
$row | integer | the row number (zero-based)
$data | mixed | the data object associated with the row

Renders a link button.

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row | integer | the row number (zero-based)
$data | mixed | the data associated with the row

Renders the data cell content. This method renders the view, update and delete buttons in the data cell.


CCheckBoxColumn

Package | zii.widgets.grid
Inheritance | class CCheckBoxColumn » CGridColumn » CComponent
Since | 1.1
Version | $Id: CCheckBoxColumn.php 144 2010-03-11 21:28:29Z qiang.xue $
CCheckBoxColumn represents a grid view column of checkboxes.

CCheckBoxColumn supports single selection and multiple selection. The mode is determined according to CGridView::selectableRows. When in multiple selection mode, the header cell will display an additional checkbox, clicking on which will check or uncheck all of the checkboxes in the data cells.

By default, the checkboxes rendered in data cells will have the values that are the same as the key values of the data model. One may change this by setting either name or value.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
checkBoxHtmlOptions | array | the HTML options for the checkboxes. | CCheckBoxColumn
cssClassExpression | string | a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. | CGridColumn
footer | string | the footer cell text. | CGridColumn
footerHtmlOptions | array | the HTML options for the footer cell tag. | CGridColumn
grid | CGridView | the grid view object that owns this column. | CGridColumn
hasFooter | boolean | whether this column has a footer cell. | CGridColumn
header | string | the header cell text. | CGridColumn
headerHtmlOptions | array | the HTML options for the header cell tag. | CGridColumn
htmlOptions | array | the HTML options for the data cell tags. | CGridColumn
id | string | the ID of this column. | CGridColumn
name | string | the attribute name of the data model. | CCheckBoxColumn
value | string | a PHP expression that will be evaluated for every data cell and whose result will be rendered in each data cell as the checkbox value. | CCheckBoxColumn
visible | boolean | whether this column is visible. | CGridColumn

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGridColumn
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasFooter() |  | CGridColumn
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column. | CCheckBoxColumn
raiseEvent() | Raises an event. | CComponent
renderDataCell() | Renders a data cell. | CGridColumn
renderFilterCell() | Renders the filter cell. | CGridColumn
renderFooterCell() | Renders the footer cell. | CGridColumn
renderHeaderCell() | Renders the header cell. | CGridColumn

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderDataCellContent() | Renders the data cell content. | CCheckBoxColumn
renderFilterCellContent() | Renders the filter cell content. | CGridColumn
renderFooterCellContent() | Renders the footer cell content. | CGridColumn
renderHeaderCellContent() | Renders the header cell content. | CCheckBoxColumn

Property Details

checkBoxHtmlOptions property
public array $checkBoxHtmlOptions;

the HTML options for the checkboxes.

name property
public string $name;

the attribute name of the data model. The corresponding attribute value will be rendered in each data cell as the checkbox value. Note that if value is specified, this property will be ignored.

See Also

  • value
value property
public string $value;

a PHP expression that will be evaluated for every data cell and whose result will be rendered in each data cell as the checkbox value. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

Method Details

init() method
public void init()

Initializes the column. This method registers necessary client script for the checkbox column.

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row | integer | the row number (zero-based)
$data | mixed | the data associated with the row

Renders the data cell content. This method renders a checkbox in the data cell.

renderHeaderCellContent() method
protected void renderHeaderCellContent()

Renders the header cell content. This method will render a checkbox in the header when CGridView::selectableRows is greater than 1.


CDataColumn

Package | zii.widgets.grid
Inheritance | class CDataColumn » CGridColumn » CComponent
Since | 1.1
Version | $Id: CDataColumn.php 124 2010-02-04 02:44:56Z qiang.xue $
CDataColumn represents a grid view column that is associated with a data attribute or expression.

Either name or value should be specified. The former specifies a data attribute name, while the latter a PHP expression whose value should be rendered instead.

The property sortable determines whether the grid view can be sorted according to this column. Note that the name should always be set if the column needs to be sortable. The name value will be used by CSort to render a clickable link in the header cell to trigger the sorting.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
cssClassExpression | string | a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. | CGridColumn
filter | mixed | the HTML code representing a filter input (e. | CDataColumn
footer | string | the footer cell text. | CGridColumn
footerHtmlOptions | array | the HTML options for the footer cell tag. | CGridColumn
grid | CGridView | the grid view object that owns this column. | CGridColumn
hasFooter | boolean | whether this column has a footer cell. | CGridColumn
header | string | the header cell text. | CGridColumn
headerHtmlOptions | array | the HTML options for the header cell tag. | CGridColumn
htmlOptions | array | the HTML options for the data cell tags. | CGridColumn
id | string | the ID of this column. | CGridColumn
name | string | the attribute name of the data model. | CDataColumn
sortable | boolean | whether the column is sortable. | CDataColumn
type | string | the type of the attribute value. | CDataColumn
value | string | a PHP expression that will be evaluated for every data cell and whose result will be rendered as the content of the data cells. | CDataColumn
visible | boolean | whether this column is visible. | CGridColumn

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGridColumn
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasFooter() |  | CGridColumn
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column. | CDataColumn
raiseEvent() | Raises an event. | CComponent
renderDataCell() | Renders a data cell. | CGridColumn
renderFilterCell() | Renders the filter cell. | CGridColumn
renderFooterCell() | Renders the footer cell. | CGridColumn
renderHeaderCell() | Renders the header cell. | CGridColumn

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderDataCellContent() | Renders the data cell content. | CDataColumn
renderFilterCellContent() | Renders the filter cell content. | CDataColumn
renderFooterCellContent() | Renders the footer cell content. | CGridColumn
renderHeaderCellContent() | Renders the header cell content. | CDataColumn

Property Details

filter property (available since v1.1.1)
public mixed $filter;

the HTML code representing a filter input (e.g. a text field, a dropdown list) that is used for this data column. This property is effective only when CGridView::enableFiltering is set true. If this property is not set, a text field will be generated as the filter input; If this property is an array, a dropdown list will be generated that uses this property value as the list options.

name property
public string $name;

the attribute name of the data model. The corresponding attribute value will be rendered in each data cell. If value is specified, this property will be ignored unless the column needs to be sortable.

See Also

  • value
  • sortable
sortable property
public boolean $sortable;

whether the column is sortable. If so, the header celll will contain a link that may trigger the sorting. Defaults to true. Note that if name is not set, or if name is not allowed by CSort, this property will be treated as false.

See Also

  • name
type property
public string $type;

the type of the attribute value. This determines how the attribute value is formatted for display. Valid values include those recognizable by CGridView::formatter, such as: raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url. For more details, please refer to CFormatter. Defaults to 'text' which means the attribute value will be HTML-encoded.

value property
public string $value;

a PHP expression that will be evaluated for every data cell and whose result will be rendered as the content of the data cells. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

Method Details

init() method
public void init()

Initializes the column.

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row | integer | the row number (zero-based)
$data | mixed | the data associated with the row

Renders the data cell content. This method evaluates value or name and renders the result.

renderFilterCellContent() method (available since v1.1.1)
protected void renderFilterCellContent()

Renders the filter cell content. This method will render the filter as is if it is a string. If filter is an array, it is assumed to be a list of options, and a dropdown selector will be rendered. Otherwise if filter is not false, a text field is rendered.

renderHeaderCellContent() method
protected void renderHeaderCellContent()

Renders the header cell content. This method will render a link that can trigger the sorting if the column is sortable.


CGridColumn

Package | zii.widgets.grid
Inheritance | abstract class CGridColumn » CComponent
Subclasses | CButtonColumn, CCheckBoxColumn, CDataColumn, CLinkColumn
Since | 1.1
Version | $Id: CGridColumn.php 114 2010-01-20 02:24:05Z qiang.xue $
CGridColumn is the base class for all grid view column classes.

A CGridColumn object represents the specification for rendering the cells in a particular grid view column.

In a column, there is one header cell, multiple data cells, and an optional footer cell. Child classes may override renderHeaderCellContent, renderDataCellContent and renderFooterCellContent to customize how these cells are rendered.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
cssClassExpression | string | a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. | CGridColumn
footer | string | the footer cell text. | CGridColumn
footerHtmlOptions | array | the HTML options for the footer cell tag. | CGridColumn
grid | CGridView | the grid view object that owns this column. | CGridColumn
hasFooter | boolean | whether this column has a footer cell. | CGridColumn
header | string | the header cell text. | CGridColumn
headerHtmlOptions | array | the HTML options for the header cell tag. | CGridColumn
htmlOptions | array | the HTML options for the data cell tags. | CGridColumn
id | string | the ID of this column. | CGridColumn
visible | boolean | whether this column is visible. | CGridColumn

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGridColumn
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasFooter() |  | CGridColumn
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column. | CGridColumn
raiseEvent() | Raises an event. | CComponent
renderDataCell() | Renders a data cell. | CGridColumn
renderFilterCell() | Renders the filter cell. | CGridColumn
renderFooterCell() | Renders the footer cell. | CGridColumn
renderHeaderCell() | Renders the header cell. | CGridColumn

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderDataCellContent() | Renders the data cell content. | CGridColumn
renderFilterCellContent() | Renders the filter cell content. | CGridColumn
renderFooterCellContent() | Renders the footer cell content. | CGridColumn
renderHeaderCellContent() | Renders the header cell content. | CGridColumn

Property Details

cssClassExpression property
public string $cssClassExpression;

a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

footer property
public string $footer;

the footer cell text. Note that it will not be HTML-encoded.

footerHtmlOptions property
public array $footerHtmlOptions;

the HTML options for the footer cell tag.

grid property
public CGridView $grid;

the grid view object that owns this column.

hasFooter property read-only
public boolean getHasFooter()

whether this column has a footer cell. This is determined based on whether footer is set.

header property
public string $header;

the header cell text. Note that it will not be HTML-encoded.

headerHtmlOptions property
public array $headerHtmlOptions;

the HTML options for the header cell tag.

htmlOptions property
public array $htmlOptions;

the HTML options for the data cell tags.

id property
public string $id;

the ID of this column. This value should be unique among all grid view columns. If this is set, it will be assigned one automatically.

visible property
public boolean $visible;

whether this column is visible. Defaults to true.

Method Details

__construct() method
public void __construct(CGridView $grid)
$grid CGridView the grid view that owns this column.

Constructor.

getHasFooter() method
public boolean getHasFooter()
{return} boolean whether this column has a footer cell. This is determined based on whether footer is set.

init() method
public void init()

Initializes the column. This method is invoked by the grid view when it initializes itself before rendering. You may override this method to prepare the column for rendering.

renderDataCell() method
public void renderDataCell(integer $row)
$row integer the row number (zero-based)

Renders a data cell.

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row | integer | the row number (zero-based)
$data | mixed | the data associated with the row

Renders the data cell content. This method SHOULD be overridden to customize the rendering of the data cell.

renderFilterCell() method (available since v1.1.1)
public void renderFilterCell()

Renders the filter cell.

renderFilterCellContent() method (available since v1.1.1)
protected void renderFilterCellContent()

Renders the filter cell content. The default implementation simply renders a space. This method may be overridden to customize the rendering of the filter cell (if any).

renderFooterCell() method
public void renderFooterCell()

Renders the footer cell.

renderFooterCellContent() method
protected void renderFooterCellContent()

Renders the footer cell content. The default implementation simply renders footer. This method may be overridden to customize the rendering of the footer cell.

renderHeaderCell() method
public void renderHeaderCell()

Renders the header cell.

renderHeaderCellContent() method
protected void renderHeaderCellContent()

Renders the header cell content. The default implementation simply renders header. This method may be overridden to customize the rendering of the header cell.


CGridView

Package | zii.widgets.grid
Inheritance | class CGridView » CBaseListView » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CGridView.php 130 2010-02-26 14:19:53Z qiang.xue $
CGridView displays a list of data items in terms of a table.

Each row of the table represents the data of a single data item, and a column usually represents an attribute of the item (some columns may correspond to complex expression of attributes or static text).

CGridView supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode or normal page request. A benefit of using CGridView is that when the user browser disables JavaScript, the sorting and pagination automatically degenerate to normal page requests and are still functioning as expected.

CGridView should be used together with a data provider, preferrably a CActiveDataProvider.

The minimal code needed to use CGridView is as follows:

$dataProvider=new CActiveDataProvider('Post');

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
));

The above code first creates a data provider for the Post ActiveRecord class. It then uses CGridView to display every attribute in every Post instance. The displayed table is equiped with sorting and pagination functionality.

In order to selectively display attributes with different formats, we may configure the CGridView::columns property. For example, we may specify only the title and create_time attributes to be displayed, and the create_time should be properly formatted to show as a time. We may also display the attributes of the related objects using the dot-syntax as shown below:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'title',          // display the 'title' attribute
        'category.name',  // display the 'name' attribute of the 'category' relation
        'content:html',   // display the 'content' attribute as purified HTML
        array(            // display 'create_time' using an expression
            'name'=>'create_time',
            'value'=>'date("M j, Y", $data->create_time)',
        ),
        array(            // display 'author.username' using an expression
            'name'=>'authorName',
            'value'=>'$data->author->username',
        ),
        array(            // display a column with "view", "update" and "delete" buttons
            'class'=>'CButtonColumn',
        ),
    ),
));

Please refer to columns for more details about how to configure this property.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
afterAjaxUpdate | string | a javascript function that will be invoked after a successful AJAX response is received. | CGridView
ajaxUpdate | mixed | the ID of the container whose content may be updated with an AJAX response. | CGridView
ajaxVar | string | the name of the GET variable that indicates the request is an AJAX request triggered by this widget. | CGridView
baseScriptUrl | string | the base script URL for all grid view resources (e. | CGridView
beforeAjaxUpdate | string | a javascript function that will be invoked before an AJAX update occurs. | CGridView
columns | array | grid column configuration. | CGridView
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | string | the URL of the CSS file used by this grid view. | CGridView
dataProvider | IDataProvider | the data provider for the view. | CBaseListView
emptyText | string | the message to be displayed when dataProvider does not have any data. | CBaseListView
enablePagination | boolean | whether to enable pagination. | CBaseListView
enableSorting | boolean | whether to enable sorting. | CBaseListView
filter | CModel | the model instance that keeps the user-entered filter data. | CGridView
filterCssClass | string | the CSS class name for the table row element containing all filter input fields. | CGridView
filterPosition | string | whether the filters should be displayed in the grid view. | CGridView
formatter | CFormatter | the formatter instance. | CGridView
hasFooter | boolean | whether the table should render a footer. | CGridView
hideHeader | boolean | whether to hide the header cells of the grid. | CGridView
htmlOptions | array | the HTML options for the view container tag. | CBaseListView
id | string | id of the widget. | CWidget
itemsCssClass | string | the CSS class name for the container of all data item display. | CBaseListView
loadingCssClass | string | the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. | CBaseListView
nullDisplay | string | the text to be displayed in a data cell when a data value is null. | CGridView
owner | CBaseController | owner/creator of this widget. | CWidget
pager | array | the configuration for the pager. | CBaseListView
pagerCssClass | string | the CSS class name for the pager container. | CBaseListView
rowCssClass | array | the CSS class names for the table body rows. | CGridView
rowCssClassExpression | string | a PHP expression that is evaluated for every table body row and whose result is used as the CSS class name for the row. | CGridView
selectableRows | integer | the number of table body rows that can be selected. | CGridView
selectionChanged | string | a javascript function that will be invoked after the row selection is changed. | CGridView
showTableOnEmpty | boolean | whether to display the table even when there is no data. | CGridView
skin | mixed | the name of the skin to be used by this widget. | CWidget
summaryCssClass | string | the CSS class name for the summary text container. | CBaseListView
summaryText | string | the summary text template for the view. | CBaseListView
tagName | string | the tag name for the view container. | CBaseListView
template | string | the template to be used to control the layout of various sections in the view. | CBaseListView
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getFormatter() |  | CGridView
getHasFooter() |  | CGridView
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the grid view. | CGridView
raiseEvent() | Raises an event. | CComponent
registerClientScript() | Registers necessary client scripts. | CGridView
render() | Renders a view. | CWidget
renderContent() | Renders the main content of the view. | CBaseListView
renderEmptyText() | Renders the empty message when there is no data. | CBaseListView
renderFile() | Renders a view file. | CBaseController
renderFilter() | Renders the filter. | CGridView
renderInternal() | Renders a view file. | CBaseController
renderItems() | Renders the data items for the grid view. | CGridView
renderKeys() | Renders the key values of the data in a hidden tag. | CBaseListView
renderPager() | Renders the pager. | CBaseListView
renderSummary() | Renders the summary text. | CBaseListView
renderTableBody() | Renders the table body. | CGridView
renderTableFooter() | Renders the table footer. | CGridView
renderTableHeader() | Renders the table header. | CGridView
renderTableRow() | Renders a table body row. | CGridView
run() | Renders the view. | CBaseListView
setFormatter() |  | CGridView
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
createDataColumn() | Creates a CDataColumn based on a shortcut column specification string. | CGridView
initColumns() | Creates column objects and initializes them. | CGridView
renderSection() | Renders a section. | CBaseListView

Property Details

afterAjaxUpdate property
public string $afterAjaxUpdate;

a javascript function that will be invoked after a successful AJAX response is received. The function signature is function(id, data) where 'id' refers to the ID of the grid view 'data' the received ajax response data.

ajaxUpdate property
public mixed $ajaxUpdate;

the ID of the container whose content may be updated with an AJAX response. Defaults to null, meaning the container for this grid view instance. If it is set false, it means sorting and pagination will be performed in normal page requests instead of AJAX requests. If the sorting and pagination should trigger the update of multiple containers' content in AJAX fashion, these container IDs may be listed here (separated with comma).

ajaxVar property
public string $ajaxVar;

the name of the GET variable that indicates the request is an AJAX request triggered by this widget. Defaults to 'ajax'. This is effective only when ajaxUpdate is not false.

baseScriptUrl property
public string $baseScriptUrl;

the base script URL for all grid view resources (e.g. javascript, CSS file, images). Defaults to null, meaning using the integrated grid view resources (which are published as assets).

beforeAjaxUpdate property
public string $beforeAjaxUpdate;

a javascript function that will be invoked before an AJAX update occurs. The function signature is function(id) where 'id' refers to the ID of the grid view.

columns property
public array $columns;

grid column configuration. Each array element represents the configuration for one particular grid column which can be either a string or an array.

When a column is specified as a string, it should be in the format of "name:type:header", where "type" and "header" are optional. A CDataColumn instance will be created in this case, whose CDataColumn::name, CDataColumn::type and CDataColumn::header properties will be initialized accordingly.

When a column is specified as an array, it will be used to create a grid column instance, where the 'class' element specifies the column class name (defaults to CDataColumn if absent). Currently, these official column classes are provided: CDataColumn, CLinkColumn, CButtonColumn and CCheckBoxColumn.

cssFile property
public string $cssFile;

the URL of the CSS file used by this grid view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

filter property (available since v1.1.1)
public CModel $filter;

the model instance that keeps the user-entered filter data. When this property is set, the grid view will enable column-based filtering. Each data column by default will display a text field at the top that users can fill in to filter the data.

filterCssClass property (available since v1.1.1)
public string $filterCssClass;

the CSS class name for the table row element containing all filter input fields. Defaults to 'filters'.

See Also

  • filter
filterPosition property (available since v1.1.1)
public string $filterPosition;

whether the filters should be displayed in the grid view. Valid values include:

  • header: the filters will be displayed on top of each column's header cell.
  • body: the filters will be displayed right below each column's header cell.
  • footer: the filters will be displayed below each column's footer cell.

See Also

  • filter
formatter property
public CFormatter getFormatter()
public void setFormatter(CFormatter $value)

the formatter instance. Defaults to the 'format' application component.

hasFooter property read-only
public boolean getHasFooter()

whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value.

hideHeader property (available since v1.1.1)
public boolean $hideHeader;

whether to hide the header cells of the grid. When this is true, header cells will not be rendered, which means the grid cannot be sorted anymore since the sort links are located in the header. Defaults to false.

nullDisplay property
public string $nullDisplay;

the text to be displayed in a data cell when a data value is null. This property will NOT be HTML-encoded when rendering. Defaults to an HTML blank.

rowCssClass property
public array $rowCssClass;

the CSS class names for the table body rows. If multiple CSS class names are given, they will be assigned to the rows sequentially and repeatedly. This property is ignored if rowCssClassExpression is set. Defaults to array('odd', 'even').

See Also

  • rowCssClassExpression
rowCssClassExpression property
public string $rowCssClassExpression;

a PHP expression that is evaluated for every table body row and whose result is used as the CSS class name for the row. In this expression, the variable $row stands for the row number (zero-based), $data is the data model associated with the row, and $this is the grid object.

See Also

  • rowCssClass
selectableRows property
public integer $selectableRows;

the number of table body rows that can be selected. If 0, it means rows cannot be selected. If 1, only one row can be selected. If 2 or any other number, it means multiple rows can be selected. A selected row will have a CSS class named 'selected'. You may also call the JavaScript function $.fn.yiiGridView.getSelection(containerID) to retrieve the key values of the selected rows.

selectionChanged property
public string $selectionChanged;

a javascript function that will be invoked after the row selection is changed. The function signature is function(id) where 'id' refers to the ID of the grid view. In this function, you may use $.fn.yiiGridView.getSelection(id) to get the key values of the currently selected rows.

See Also

  • selectableRows
showTableOnEmpty property
public boolean $showTableOnEmpty;

whether to display the table even when there is no data. Defaults to true. The emptyText will be displayed to indicate there is no data.

Method Details

createDataColumn() method
protected CDataColumn createDataColumn(string $text)
$text | string | the column specification string
{return} | CDataColumn | the column instance

Creates a CDataColumn based on a shortcut column specification string.

getFormatter() method
public CFormatter getFormatter()
{return} CFormatter the formatter instance. Defaults to the 'format' application component.

getHasFooter() method
public boolean getHasFooter()
{return} boolean whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value.

init() method
public void init()

Initializes the grid view. This method will initialize required property values and instantiate columns objects.

initColumns() method
protected void initColumns()

Creates column objects and initializes them.

registerClientScript() method
public void registerClientScript()

Registers necessary client scripts.

renderFilter() method (available since v1.1.1)
public void renderFilter()

Renders the filter.

renderItems() method
public void renderItems()

Renders the data items for the grid view.

renderTableBody() method
public void renderTableBody()

Renders the table body.

renderTableFooter() method
public void renderTableFooter()

Renders the table footer.

renderTableHeader() method
public void renderTableHeader()

Renders the table header.

renderTableRow() method
public void renderTableRow(integer $row)
$row integer the row number (zero-based).

Renders a table body row.

setFormatter() method
public void setFormatter(CFormatter $value)
$value CFormatter the formatter instance


CLinkColumn

Package | zii.widgets.grid
Inheritance | class CLinkColumn » CGridColumn » CComponent
Since | 1.1
Version | $Id: CLinkColumn.php 107 2010-01-13 16:04:23Z qiang.xue $
CLinkColumn represents a grid view column that renders a hyperlink in each of its data cells.

The label and url properties determine how each hyperlink will be rendered. The labelExpression, urlExpression properties may be used instead if they are available. In addition, if imageUrl is set, an image link will be rendered.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
cssClassExpression | string | a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. | CGridColumn
footer | string | the footer cell text. | CGridColumn
footerHtmlOptions | array | the HTML options for the footer cell tag. | CGridColumn
grid | CGridView | the grid view object that owns this column. | CGridColumn
hasFooter | boolean | whether this column has a footer cell. | CGridColumn
header | string | the header cell text. | CGridColumn
headerHtmlOptions | array | the HTML options for the header cell tag. | CGridColumn
htmlOptions | array | the HTML options for the data cell tags. | CGridColumn
id | string | the ID of this column. | CGridColumn
imageUrl | string | the URL to the image. | CLinkColumn
label | string | the label to the hyperlinks in the data cells. | CLinkColumn
labelExpression | string | a PHP expression that will be evaluated for every data cell and whose result will be rendered as the label of the hyperlink of the data cells. | CLinkColumn
linkHtmlOptions | array | the HTML options for the hyperlinks | CLinkColumn
url | string | the URL of the hyperlinks in the data cells. | CLinkColumn
urlExpression | string | a PHP expression that will be evaluated for every data cell and whose result will be rendered as the URL of the hyperlink of the data cells. | CLinkColumn
visible | boolean | whether this column is visible. | CGridColumn

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CGridColumn
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getHasFooter() |  | CGridColumn
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the column. | CGridColumn
raiseEvent() | Raises an event. | CComponent
renderDataCell() | Renders a data cell. | CGridColumn
renderFilterCell() | Renders the filter cell. | CGridColumn
renderFooterCell() | Renders the footer cell. | CGridColumn
renderHeaderCell() | Renders the header cell. | CGridColumn

Protected Methods

Hide inherited methods

Method | Description | Defined By
renderDataCellContent() | Renders the data cell content. | CLinkColumn
renderFilterCellContent() | Renders the filter cell content. | CGridColumn
renderFooterCellContent() | Renders the footer cell content. | CGridColumn
renderHeaderCellContent() | Renders the header cell content. | CGridColumn

Property Details

imageUrl property
public string $imageUrl;

the URL to the image. If this is set, an image link will be rendered.

label property
public string $label;

the label to the hyperlinks in the data cells. Note that the label will not be HTML-encoded when rendering. This property is ignored if labelExpression is set.

See Also

  • labelExpression
labelExpression property
public string $labelExpression;

a PHP expression that will be evaluated for every data cell and whose result will be rendered as the label of the hyperlink of the data cells. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

linkHtmlOptions property
public array $linkHtmlOptions;

the HTML options for the hyperlinks

url property
public string $url;

the URL of the hyperlinks in the data cells. This property is ignored if urlExpression is set.

See Also

  • urlExpression
urlExpression property
public string $urlExpression;

a PHP expression that will be evaluated for every data cell and whose result will be rendered as the URL of the hyperlink of the data cells. In this expression, the variable $row the row number (zero-based); $data the data model for the row; and $this the column object.

Method Details

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row | integer | the row number (zero-based)
$data | mixed | the data associated with the row

Renders the data cell content. This method renders a hyperlink in the data cell.


CJuiAccordion

Package | zii.widgets.jui
Inheritance | class CJuiAccordion » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiAccordion.php 127 2010-02-18 14:03:04Z sebathi $
CJuiAccordion displays an accordion widget.

CJuiAccordion encapsulates the JUI Accordion plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiAccordion', array(
    'panels'=>array(
        'panel 1'=>'content for panel 1',
        'panel 2'=>'content for panel 2',
        // panel 3 contains the content rendered by a partial view
        'panel 3'=>$this->renderPartial('_partial',null,true),
    ),
    // additional javascript options for the accordion plugin
    'options'=>array(
        'animated'=>'bounceslide',
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI accordion plugin. Please refer to the JUI Accordion documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
contentTemplate | string | the template that is used to generated every panel content. | CJuiAccordion
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
headerTemplate | string | the template that is used to generated every panel header. | CJuiAccordion
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
panels | array | list of panels (panel title=>panel content). | CJuiAccordion
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains all panels. | CJuiAccordion
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiAccordion
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

contentTemplate property
public string $contentTemplate;

the template that is used to generated every panel content. The token "{content}" in the template will be replaced with the panel content.

headerTemplate property
public string $headerTemplate;

the template that is used to generated every panel header. The token "{title}" in the template will be replaced with the panel title. Note that if you make change to this template, you may also need to adjust the 'header' setting in options.

panels property
public array $panels;

list of panels (panel title=>panel content). Note that neither panel title nor panel content will be HTML-encoded.

tagName property
public string $tagName;

the name of the container element that contains all panels. Defaults to 'div'.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiDatePicker

Package | zii.widgets.jui
Inheritance | class CJuiDatePicker » CJuiInputWidget » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiDatePicker.php 135 2010-02-28 16:05:28Z sebathi $
CJuiDatePicker displays a datepicker.

CJuiDatePicker encapsulates the JUI datepicker plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'publishDate',
    // additional javascript options for the date picker plugin
    'options'=>array(
        'showAnim'=>'fold',
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI datepicker plugin. Please refer to the JUI datepicker documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CJuiInputWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
defaultOptions | array | The default options called just one time per request. | CJuiDatePicker
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
i18nScriptFile | string | The i18n Jquery UI script file. | CJuiDatePicker
id | string | id of the widget. | CWidget
language | string | the locale ID (e. | CJuiDatePicker
model | CModel | the data model associated with this widget. | CJuiInputWidget
name | string | the input name. | CJuiInputWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
value | string | the input value | CJuiInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiDatePicker
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
hasModel() |  | CJuiInputWidget
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolveNameID() |  | CJuiInputWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

defaultOptions property
public array $defaultOptions;

The default options called just one time per request. This options will alter every other CJuiDatePicker instance in the page. It has to be set at the first call of CJuiDatePicker widget in the request.

i18nScriptFile property
public string $i18nScriptFile;

The i18n Jquery UI script file. It uses scriptUrl property as base url.

language property
public string $language;

the locale ID (e.g. 'fr', 'de') for the language to be used by the date picker. If this property is not set, I18N will not be involved. That is, the date picker will show in English.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiDialog

Package | zii.widgets.jui
Inheritance | class CJuiDialog » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiDialog.php 127 2010-02-18 14:03:04Z sebathi $
CJuiDialog displays a dialog widget.

CJuiDialog encapsulates the JUI Dialog plugin.

To use this widget, you may insert the following code in a view:
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'mydialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'Dialog box 1',
        'autoOpen'=>false,
    ),
));

    echo 'dialog content here';

$this->endWidget('zii.widgets.jui.CJuiDialog');

// the link that may open the dialog
echo CHtml::link('open dialog', '#', array(
   'onclick'=>'$("#mydialog").dialog("open"); return false;',
));

By configuring the options property, you may specify the options that need to be passed to the JUI dialog plugin. Please refer to the JUI Dialog documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains all panels. | CJuiDialog
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Renders the open tag of the dialog. | CJuiDialog
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the close tag of the dialog. | CJuiDialog
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the name of the container element that contains all panels. Defaults to 'div'.

Method Details

init() method
public void init()

Renders the open tag of the dialog. This method also registers the necessary javascript code.

run() method
public void run()

Renders the close tag of the dialog.


CJuiDraggable

Package | zii.widgets.jui
Inheritance | class CJuiDraggable » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiDraggable.php 127 2010-02-18 14:03:04Z sebathi $
CJuiDraggable displays a draggable widget.

CJuiDraggable encapsulates the JUI Draggable plugin.

To use this widget, you may insert the following code in a view:
$this->beginWidget('zii.widgets.jui.CJuiDraggable', array(
    // additional javascript options for the draggable plugin
    'options'=>array(
        'scope'=>'myScope',
    ),
));
    echo 'Your draggable content here';

$this->endWidget();

By configuring the options property, you may specify the options that need to be passed to the JUI Draggable plugin. Please refer to the JUI Draggable documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the Draggable element. | CJuiDraggable
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Renders the open tag of the draggable element. | CJuiDraggable
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the close tag of the draggable element. | CJuiDraggable
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the name of the Draggable element. Defaults to 'div'.

Method Details

init() method
public void init()

Renders the open tag of the draggable element. This method also registers the necessary javascript code.

run() method
public void run()

Renders the close tag of the draggable element.


CJuiDroppable

Package | zii.widgets.jui
Inheritance | class CJuiDroppable » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiDroppable.php 127 2010-02-18 14:03:04Z sebathi $
CJuiDroppable displays a droppable widget.

CJuiDroppable encapsulates the JUI Droppable plugin.

To use this widget, you may insert the following code in a view:
$this->beginWidget('zii.widgets.jui.CJuiDroppable', array(
    // additional javascript options for the droppable plugin
    'options'=>array(
        'scope'=>'myScope',
    ),
));
    echo 'Your droppable content here';

$this->endWidget();

By configuring the options property, you may specify the options that need to be passed to the JUI Droppable plugin. Please refer to the JUI Droppable documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the HTML tag name of the Droppable element. | CJuiDroppable
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Renders the open tag of the droppable element. | CJuiDroppable
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the close tag of the droppable element. | CJuiDroppable
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the HTML tag name of the Droppable element. Defaults to 'div'.

Method Details

init() method
public void init()

Renders the open tag of the droppable element. This method also registers the necessary javascript code.

run() method
public void run()

Renders the close tag of the droppable element.


CJuiInputWidget

Package | zii.widgets.jui
Inheritance | abstract class CJuiInputWidget » CJuiWidget » CWidget » CBaseController » CComponent
Subclasses | CJuiDatePicker, CJuiSliderInput
Since | 1.1
Version | $Id: CJuiInputWidget.php 99 2010-01-07 20:55:13Z qiang.xue $
CJuiInputWidget is the base class for JUI widgets that can collect user input.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CJuiInputWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
model | CModel | the data model associated with this widget. | CJuiInputWidget
name | string | the input name. | CJuiInputWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
value | string | the input value | CJuiInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
hasModel() |  | CJuiInputWidget
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolveNameID() |  | CJuiInputWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

attribute property
public string $attribute;

the attribute associated with this widget. The name can contain square brackets (e.g. 'name[1]') which is used to collect tabular data input.

model property
public CModel $model;

the data model associated with this widget.

name property
public string $name;

the input name. This must be set if model is not set.

value property
public string $value;

the input value

Method Details

hasModel() method
protected boolean hasModel()
{return} boolean whether this widget is associated with a data model.

resolveNameID() method
protected array resolveNameID()
{return} array the name and the ID of the input.


CJuiProgressBar

Package | zii.widgets.jui
Inheritance | class CJuiProgressBar » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiProgressBar.php 127 2010-02-18 14:03:04Z sebathi $
CJuiProgressBar displays a progress bar widget.

CJuiProgressBar encapsulates the JUI Progressbar plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiProgressBar', array(
    'value'=>75,
    // additional javascript options for the progress bar plugin
    'options'=>array(
        'change'=>'js:function(event, ui) {...}',
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI progressbar plugin. Please refer to the JUI Progressbar documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains the progress bar. | CJuiProgressBar
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
value | integer | the percentage of the progress. | CJuiProgressBar
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiProgressBar
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the name of the container element that contains the progress bar. Defaults to 'div'.

value property
public integer $value;

the percentage of the progress. This must be an integer between 0 and 100. Defaults to 0.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiResizable

Package | zii.widgets.jui
Inheritance | class CJuiResizable » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiResizable.php 143 2010-03-11 13:09:59Z qiang.xue $
CJuiResizable displays a resizable widget.

CJuiResizable encapsulates the JUI Resizable plugin.

To use this widget, you may insert the following code in a view:
$this->beginWidget('zii.widgets.jui.CJuiResizable', array(
    // additional javascript options for the resizable plugin
    'options'=>array(
        'minHeight'=>'150',
    ),
));
    echo 'Your Resizable content here';

$this->endWidget();

By configuring the options property, you may specify the options that need to be passed to the JUI Resizable plugin. Please refer to the JUI Resizable documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the Resizable element. | CJuiResizable
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Renders the open tag of the resizable element. | CJuiResizable
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Renders the close tag of the resizable element. | CJuiResizable
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the name of the Resizable element. Defaults to 'div'.

Method Details

init() method
public void init()

Renders the open tag of the resizable element. This method also registers the necessary javascript code.

run() method
public void run()

Renders the close tag of the resizable element.


CJuiSelectable

Package | zii.widgets.jui
Inheritance | class CJuiSelectable » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiSelectable.php 143 2010-03-11 13:09:59Z qiang.xue $
CJuiSelectable displays an accordion widget.

CJuiSelectable encapsulates the JUI Selectable plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiSelectable', array(
    'items'=>array(
        'id1'=>'Item 1',
        'id2'=>'Item 2',
        'id3'=>'Item 3',
    ),
    // additional javascript options for the selectable plugin
    'options'=>array(
        'delay'=>'300',
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI Selectable plugin. Please refer to the JUI Selectable documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
itemTemplate | string | the template that is used to generated every selectable item. | CJuiSelectable
items | array | list of selectable items (id=>item content). | CJuiSelectable
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains all items. | CJuiSelectable
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiSelectable
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

itemTemplate property
public string $itemTemplate;

the template that is used to generated every selectable item. The token "{content}" in the template will be replaced with the item content, while "{id}" will be replaced with the item ID.

items property
public array $items;

list of selectable items (id=>item content). Note that the item contents will not be HTML-encoded.

tagName property
public string $tagName;

the name of the container element that contains all items. Defaults to 'ul'.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiSlider

Package | zii.widgets.jui
Inheritance | class CJuiSlider » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiSlider.php 143 2010-03-11 13:09:59Z qiang.xue $
CJuiSlider displays a slider.

CJuiSlider encapsulates the JUI slider plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiSlider', array(
    'value'=>37,
    // additional javascript options for the slider plugin
    'options'=>array(
        'min'=>10,
        'max'=>50,
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI slider plugin. Please refer to the JUI slider documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains the slider. | CJuiSlider
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
value | integer | determines the value of the slider, if there's only one handle. | CJuiSlider
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiSlider
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

tagName property
public string $tagName;

the name of the container element that contains the slider. Defaults to 'div'.

value property
public integer $value;

determines the value of the slider, if there's only one handle. If there is more than one handle, determines the value of the first handle.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiSliderInput

Package | zii.widgets.jui
Inheritance | class CJuiSliderInput » CJuiInputWidget » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiSliderInput.php 151 2010-03-14 04:19:10Z qiang.xue $
CJuiSliderInput displays a slider. It can be used in forms and post its value.

CJuiSlider encapsulates the JUI slider plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiSliderInput', array(
    'name'=>'rate',
    'value'=>37,
    // additional javascript options for the slider plugin
    'options'=>array(
        'min'=>10,
        'max'=>50,
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));

If you need to use the slider event, please change the event value for 'stop' or 'change'.

By configuring the options property, you may specify the options that need to be passed to the JUI slider plugin. Please refer to the JUI slider documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
attribute | string | the attribute associated with this widget. | CJuiInputWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
event | string | the name of the event where the input will be attached to the slider. | CJuiSliderInput
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
model | CModel | the data model associated with this widget. | CJuiInputWidget
name | string | the input name. | CJuiInputWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains the slider. | CJuiSliderInput
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
value | integer | determines the value of the slider, if there's only one handle. | CJuiInputWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiSliderInput
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
hasModel() |  | CJuiInputWidget
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolveNameID() |  | CJuiInputWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

event property
public string $event;

the name of the event where the input will be attached to the slider. It can be 'slide', 'stop' or 'change'. If you want to use 'slide' event change $event property to 'change'

tagName property
public string $tagName;

the name of the container element that contains the slider. Defaults to 'div'.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiSortable

Package | zii.widgets.jui
Inheritance | class CJuiSortable » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiSortable.php 143 2010-03-11 13:09:59Z qiang.xue $
CJuiSortable displays an accordion widget.

CJuiSortable encapsulates the JUI Sortable plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiSortable', array(
    'items'=>array(
        'id1'=>'Item 1',
        'id2'=>'Item 2',
        'id3'=>'Item 3',
    ),
    // additional javascript options for the accordion plugin
    'options'=>array(
        'delay'=>'300',
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI Sortable plugin. Please refer to the JUI Sortable documentation for possible options (name-value pairs).

If you are using javascript code anywhere in the code, please add "js:" at the start of the js code definition and Yii will use this string as js code.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
itemTemplate | string | the template that is used to generated every sortable item. | CJuiSortable
items | array | list of sortable items (id=>item content). | CJuiSortable
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tagName | string | the name of the container element that contains all items. | CJuiSortable
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiSortable
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

itemTemplate property
public string $itemTemplate;

the template that is used to generated every sortable item. The token "{content}" in the template will be replaced with the item content, while "{id}" be replaced with the item ID.

items property
public array $items;

list of sortable items (id=>item content). Note that the item contents will not be HTML-encoded.

tagName property
public string $tagName;

the name of the container element that contains all items. Defaults to 'ul'.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiTabs

Package | zii.widgets.jui
Inheritance | class CJuiTabs » CJuiWidget » CWidget » CBaseController » CComponent
Since | 1.1
Version | $Id: CJuiTabs.php 127 2010-02-18 14:03:04Z sebathi $
CJuiTabs displays a tabs widget.

CJuiTabs encapsulates the JUI tabs plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiTabs', array(
    'tabs'=>array(
        'StaticTab 1'=>'Content for tab 1',
        'StaticTab 2'=>array('content'=>'Content for tab 2', 'id'=>'tab2'),
        // panel 3 contains the content rendered by a partial view
        'AjaxTab'=>array('ajax'=>$ajaxUrl),
    ),
    // additional javascript options for the tabs plugin
    'options'=>array(
        'collapsible'=>true,
    ),
));

By configuring the options property, you may specify the options that need to be passed to the JUI tabs plugin. Please refer to the JUI tabs documentation for possible options (name-value pairs).

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
contentTemplate | string | the template that is used to generated every tab content. | CJuiTabs
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
headerTemplate | string | the template that is used to generated every panel title. | CJuiTabs
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
tabs | array | list of tabs (tab title=>tab content). | CJuiTabs
tagName | string | the name of the container element that contains all panels. | CJuiTabs
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Run this widget. | CJuiTabs
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

contentTemplate property
public string $contentTemplate;

the template that is used to generated every tab content. The token "{content}" in the template will be replaced with the panel content and the token "{id}" with the tab ID.

headerTemplate property
public string $headerTemplate;

the template that is used to generated every panel title. The token "{title}" in the template will be replaced with the panel title and the token "{url}" will be replaced with "#TabID" or with the url of the ajax request.

tabs property
public array $tabs;

list of tabs (tab title=>tab content). Note that the tab title will not be HTML-encoded. The tab content can be either a string or an array. When it is an array, it can be in one of the following two formats:

array('id'=>'myTabID', 'content'=>'tab content')
array('id'=>'myTabID', 'ajax'=>URL)
where the 'id' element is optional. The second format allows the tab content to be dynamically fetched from the specified URL via AJAX. The URL can be either a string or an array. If an array, it will be normalized into a URL using CHtml::normalizeUrl.

tagName property
public string $tagName;

the name of the container element that contains all panels. Defaults to 'div'.

Method Details

run() method
public void run()

Run this widget. This method registers necessary javascript and renders the needed HTML code.


CJuiWidget

Package | zii.widgets.jui
Inheritance | abstract class CJuiWidget » CWidget » CBaseController » CComponent
Subclasses | CJuiAccordion, CJuiDialog, CJuiDraggable, CJuiDroppable, CJuiInputWidget, CJuiProgressBar, CJuiResizable, CJuiSelectable, CJuiSlider, CJuiSortable, CJuiTabs
Since | 1.1
Version | $Id: CJuiWidget.php 150 2010-03-14 04:12:54Z qiang.xue $
This is the base class for all JUI widget classes.

Public Properties

Hide inherited properties

Property | Type | Description | Defined By
actionPrefix | string | the prefix to the IDs of the actions. | CWidget
controller | CController | the controller that this widget belongs to. | CWidget
cssFile | mixed | the theme CSS file name. | CJuiWidget
htmlOptions | array | the HTML attributes that should be rendered in the HTML tag representing the JUI widget. | CJuiWidget
id | string | id of the widget. | CWidget
options | array | the initial JavaScript options that should be passed to the JUI plugin. | CJuiWidget
owner | CBaseController | owner/creator of this widget. | CWidget
scriptFile | mixed | the main JUI JavaScript file. | CJuiWidget
scriptUrl | string | the root URL that contains all JUI JavaScript files. | CJuiWidget
skin | mixed | the name of the skin to be used by this widget. | CWidget
theme | string | the JUI theme name. | CJuiWidget
themeUrl | string | the root URL that contains all JUI theme folders. | CJuiWidget
viewPath | string | Returns the directory containing the view files for this widget. | CWidget

Public Methods

Hide inherited methods

Method | Description | Defined By
__call() | Calls the named method which is not a class method. | CComponent
__construct() | Constructor. | CWidget
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent
__isset() | Checks if a property value is null. | CComponent
__set() | Sets value of a component property. | CComponent
__unset() | Sets a component property to be null. | CComponent
actions() | Returns a list of actions that are used by this widget. | CWidget
asa() | Returns the named behavior object. | CComponent
attachBehavior() | Attaches a behavior to this component. | CComponent
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent
attachEventHandler() | Attaches an event handler to an event. | CComponent
beginCache() | Begins fragment caching. | CBaseController
beginClip() | Begins recording a clip. | CBaseController
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController
beginWidget() | Creates a widget and executes it. | CBaseController
canGetProperty() | Determines whether a property can be read. | CComponent
canSetProperty() | Determines whether a property can be set. | CComponent
createWidget() | Creates a widget and initializes it. | CBaseController
detachBehavior() | Detaches a behavior from the component. | CComponent
detachBehaviors() | Detaches all behaviors from the component. | CComponent
detachEventHandler() | Detaches an existing event handler. | CComponent
disableBehavior() | Disables an attached behavior. | CComponent
disableBehaviors() | Disables all behaviors attached to this component. | CComponent
enableBehavior() | Enables an attached behavior. | CComponent
enableBehaviors() | Enables all behaviors attached to this component. | CComponent
endCache() | Ends fragment caching. | CBaseController
endClip() | Ends recording a clip. | CBaseController
endContent() | Ends the rendering of content. | CBaseController
endWidget() | Ends the execution of the named widget. | CBaseController
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent
getController() |  | CWidget
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent
getId() |  | CWidget
getOwner() |  | CWidget
getViewFile() | Looks for the view script file according to the view name. | CWidget
getViewPath() | Returns the directory containing the view files for this widget. | CWidget
hasEvent() | Determines whether an event is defined. | CComponent
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent
hasProperty() | Determines whether a property is defined. | CComponent
init() | Initializes the widget. | CJuiWidget
raiseEvent() | Raises an event. | CComponent
render() | Renders a view. | CWidget
renderFile() | Renders a view file. | CBaseController
renderInternal() | Renders a view file. | CBaseController
run() | Executes the widget. | CWidget
setId() |  | CWidget
widget() | Creates a widget and executes it. | CBaseController

Protected Methods

Hide inherited methods

Method | Description | Defined By
registerCoreScripts() | Registers the core script files. | CJuiWidget
registerScriptFile() | Registers a JavaScript file under scriptUrl. | CJuiWidget
resolvePackagePath() | Determine the JUI package installation path. | CJuiWidget

Property Details

cssFile property
public mixed $cssFile;

the theme CSS file name. Defaults to 'jquery-ui.css'. Note the file must exist under the URL specified by themeUrl/theme. If you need to include multiple theme CSS files (e.g. during development, you want to include individual plugin CSS files), you may set this property as an array of the CSS file names. This property can also be set as false, which means the widget will not include any theme CSS file, and it is your responsibility to explicitly include it somewhere else.

htmlOptions property
public array $htmlOptions;

the HTML attributes that should be rendered in the HTML tag representing the JUI widget.

options property
public array $options;

the initial JavaScript options that should be passed to the JUI plugin.

scriptFile property
public mixed $scriptFile;

the main JUI JavaScript file. Defaults to 'jquery-ui.min.js'. Note the file must exist under the URL specified by scriptUrl. If you need to include multiple script files (e.g. during development, you want to include individual plugin script files rather than the minized JUI script file), you may set this property as an array of the script file names. This property can also be set as false, which means the widget will not include any script file, and it is your responsibility to explicitly include it somewhere else.

scriptUrl property
public string $scriptUrl;

the root URL that contains all JUI JavaScript files. If this property is not set (default), Yii will publish the JUI package included in the zii release and use that to infer the root script URL. You should set this property if you intend to use a JUI package whose version is different from the one included in zii. Note that under this URL, there must be a file whose name is specified by scriptFile. Do not append any slash character to the URL.

theme property
public string $theme;

the JUI theme name. Defaults to 'base'. Make sure that under themeUrl there is a directory whose name is the same as this property value (case-sensitive).

themeUrl property
public string $themeUrl;

the root URL that contains all JUI theme folders. If this property is not set (default), Yii will publish the JUI package included in the zii release and use that to infer the root theme URL. You should set this property if you intend to use a theme that is not found in the JUI package included in zii. Note that under this URL, there must be a directory whose name is specified by theme. Do not append any slash character to the URL.

Method Details

init() method
public void init()

Initializes the widget. This method will publish JUI assets if necessary. It will also register jquery and JUI JavaScript files and the theme CSS file. If you override this method, make sure you call the parent implementation first.

registerCoreScripts() method
protected void registerCoreScripts()

Registers the core script files. This method registers jquery and JUI JavaScript files and the theme CSS file.

registerScriptFile() method
protected void registerScriptFile(string $fileName, integer $position=2)
$fileName string JavaScript file name
$position integer the position of the JavaScript file. Valid values include the following:
  • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
  • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
  • CClientScript::POS_END : the script is inserted at the end of the body section.

Registers a JavaScript file under scriptUrl. Note that by default, the script file will be rendered at the end of a page to improve page loading speed.

resolvePackagePath() method
protected void resolvePackagePath()

Determine the JUI package installation path. This method will identify the JavaScript root URL and theme root URL. If they are not explicitly specified, it will publish the included JUI package and use that to resolve the needed paths.