Application

Type
Class
Namespace
craft\web
Inherits
craft\web\Application » yii\web\Application » yii\base\Application » yii\base\Module » yii\di\ServiceLocator » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Uses traits
craft\base\ApplicationTrait
Since
3.0

Craft Web Application class

An instance of the Web Application class is globally accessible to web requests in Craft via Craft::$app.

View source

Public Properties

PropertyDescription
aliasesarray – List of path aliases to be defined.
apicraft\services\Api – The API service
assetIndexercraft\services\AssetIndexer – The asset indexing service
assetManageryii\web\AssetManager – The asset manager application component.
assetTransformscraft\services\AssetTransforms – The asset transforms service
assetscraft\services\Assets – The assets service
authManageryii\rbac\ManagerInterface – The auth manager application component.
basePathstring – The root directory of the module.
behaviorsyii\base\Behavior – List of behaviors attached to this component
bootstraparray – List of components that should be run during the application bootstrapping process.
cacheyii\caching\CacheInterface – The cache application component.
canTestEditionsboolean
canUpgradeEditionboolean
catchAllarray – The configuration specifying a controller action which should handle all user requests.
categoriescraft\services\Categories – The categories service
charsetstring – The charset currently used for the application.
componentsarray – The list of the component definitions or the loaded component instances (ID => definition or instance).
composercraft\services\Composer – The Composer service
configcraft\services\Config – The config service
containerarray – Values given in terms of name-value pairs
contentcraft\services\Content – The content service
contentMigratorcraft\db\MigrationManager – The content migration manager
controlleryii\base\Controller – The currently active controller instance
controllerMaparray – Mapping from controller ID to controller configurations.
controllerNamespacestring – The namespace that controller classes are located in.
controllerPathstring – The directory that contains the controller classes.
dashboardcraft\services\Dashboard – The dashboard service
dbyii\db\Connection – The database connection.
defaultRoutestring – The default route of this application.
deprecatorcraft\services\Deprecator – The deprecator service
editioninteger
editionNamestring
elementIndexescraft\services\ElementIndexes – The element indexes service
elementscraft\services\Elements – The elements service
entriescraft\services\Entries – The entries service
entryRevisionscraft\services\EntryRevisions – The entry revisions service
envstring, null – The environment ID Craft is currently running in.
errorHandleryii\web\ErrorHandler, yii\console\ErrorHandler – The error handler application component.
extensionsarray – List of installed Yii extensions.
feedscraft\feeds\Feeds – The feeds service
fieldscraft\services\Fields – The fields service
formatteryii\i18n\Formatter – The formatter application component.
gccraft\services\Gc – The garbage collection service
globalscraft\services\Globals – The globals service
hasWrongEditionboolean
homeUrlstring – The homepage URL
i18nyii\i18n\I18N – The internationalization application component.
idstring – An ID that uniquely identifies this module among other modules which have the same parent.
images\craft\services\Images – The images service
infocraft\models\Info
isDbConnectionValidboolean
isInMaintenanceModeboolean
isInitializedboolean
isInstalledboolean
isLiveboolean
isMultiSiteboolean
isSystemOnboolean
languagestring – The language that is meant to be used for end users.
layoutstring, boolean – The layout that should be applied for views in this application.
layoutPathstring – The root directory of layout files.
licensedEditioninteger, null
licensedEditionNamestring, null
loadedModulesarray – List of loaded modules indexed by their class names.
localecraft\i18n\Locale – The Locale object for the target language
logyii\log\Dispatcher – The log dispatcher application component.
mailercraft\mail\Mailer – The mailer component
matrix\craft\services\Matrix – The matrix service
migratorcraft\db\MigrationManager – The application’s migration manager
minVersionRequiredstring, null – The minimum Craft build number required to update to this build.
moduleyii\base\Module – The parent module of this module.
modulesarray – The modules (indexed by their IDs).
mutexyii\mutex\Mutex – The application’s mutex service
namestring – The application name.
paramsarray – Custom module parameters (name => value).
pathcraft\services\Path – The path service
pluginStorecraft\services\PluginStore – The plugin store service
pluginscraft\services\Plugins – The plugins service
projectConfigcraft\services\ProjectConfig – The system config service
queuecraft\queue\Queue, craft\queue\QueueInterface – The queue service
relationscraft\services\Relations – The relations service
requestyii\web\Request, yii\console\Request – The request component.
requestedActionyii\base\Action – The requested Action.
requestedParamsarray – The parameters supplied to the requested action.
requestedRoutestring – The requested route
responseyii\web\Response, yii\console\Response – The response component.
routescraft\services\Routes – The routes service
runtimePathstring – The directory that stores runtime files.
schemaVersionstring, null – Craft’s schema version number.
searchcraft\services\Search – The search service
sectionscraft\services\Sections – The sections service
securityyii\base\Security – The security application component.
sessionyii\web\Session – The session component.
sitescraft\services\Sites – The sites service
sourceLanguagestring – The language that the application is written in.
stateinteger – The current application state during a request handling life cycle.
structurescraft\services\Structures – The structures service
systemMessagescraft\services\SystemMessages – The system email messages service
systemNamestring
systemSettingscraft\services\SystemSettings – The system settings service
systemUidstring, null
tagscraft\services\Tags – The tags service
targetLanguagestring
templateCachescraft\services\TemplateCaches – The template caches service
timeZonestring – The time zone used by this application.
tokenscraft\services\Tokens – The tokens service
uniqueIdstring – The unique ID of the module.
updatescraft\services\Updates – The updates service
urlManageryii\web\UrlManager – The URL manager for this application.
useryii\web\User – The user component.
userGroupscraft\services\UserGroups – The user groups service
userPermissionscraft\services\UserPermissions – The user permissions service
userscraft\services\Users – The users service
utilitiescraft\services\Utilities – The utilities service
vendorPathstring – The directory that stores vendor files.
versionstring – The version of this module.
viewyii\base\View, yii\web\View – The view application component that is used to render various view files.
viewPathstring – The root directory of view files.
volumescraft\services\Volumes – The volumes service
yiiVersionstring

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()Constructor.
__get()Returns the value of an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__unset()Sets an object property to null.
afterAction()This method is invoked right after an action within this module is executed.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
beforeAction()This method is invoked right before an action within this module is executed.
behaviors()Returns a list of behaviors that this component should behave as.
bootstrap()Initializes extensions and executes bootstrap components.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
clear()Removes the component from the locator.
coreComponents()Returns the configuration of core application components.
createController()Creates a controller instance based on the given route.
createControllerByID()Creates a controller based on the given controller ID.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
disableMaintenanceMode()Disables Maintenance Mode.
enableMaintenanceMode()Enables Maintenance Mode.
end()Terminates the application.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
get()Returns the component instance with the specified ID.
getApi()Returns the API service.
getAssetIndexer()Returns the asset indexing service.
getAssetManager()Returns the asset manager.
getAssetTransforms()Returns the asset transforms service.
getAssets()Returns the assets service.
getAuthManager()Returns the auth manager for this application.
getBasePath()Returns the root directory of the module.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getCache()Returns the cache component.
getCanTestEditions()Returns whether Craft is running on a domain that is eligible to test out the editions.
getCanUpgradeEdition()Returns whether Craft is eligible to be upgraded to a different edition.
getCategories()Returns the categories service.
getComponents()Returns the list of the component definitions or the loaded component instances.
getComposer()Returns the Composer service.
getConfig()Returns the config service.
getContent()Returns the content service.
getContentMigrator()Returns the content migration manager.
getControllerPath()Returns the directory that contains the controller classes according to controllerNamespace.
getDashboard()Returns the dashboard service.
getDb()Returns the database connection component.
getDeprecator()Returns the deprecator service.
getEdition()Returns the Craft edition.
getEditionName()Returns the name of the Craft edition.
getElementIndexes()Returns the element indexes service.
getElements()Returns the elements service.
getEntries()Returns the entries service.
getEntryRevisions()Returns the entry revisions service.
getErrorHandler()Returns the error handler component.
getFeeds()Returns the feeds service.
getFields()Returns the fields service.
getFormatter()Returns the formatter component.
getGc()Returns the garbage collection service.
getGlobals()Returns the globals service.
getHasWrongEdition()Returns whether Craft is running with the wrong edition.
getHomeUrl()
getI18n()Returns the internationalization (i18n) component.
getImages()Returns the images service.
getInfo()Returns the info model, or just a particular attribute.
getInstance()Returns the currently requested instance of this module class.
getIsInMaintenanceMode()Returns whether someone is currently performing a system update.
getIsInitialized()Returns whether Craft has been fully initialized.
getIsInstalled()Returns whether Craft is installed.
getIsLive()Returns whether the system is currently live.
getIsMultiSite()Returns whether this Craft install has multiple sites.
getIsSystemOn()Returns whether the system is currently live.
getLayoutPath()Returns the directory that contains layout view files for this module.
getLicensedEdition()Returns the edition Craft is actually licensed to run in.
getLicensedEditionName()Returns the name of the edition Craft is actually licensed to run in.
getLocale()Returns a Locale object for the target language.
getLog()Returns the log dispatcher component.
getMailer()Returns the current mailer.
getMatrix()Returns the matrix service.
getMigrator()Returns the application’s migration manager.
getModule()Retrieves the child module of the specified ID.
getModules()Returns the sub-modules in this module.
getMutex()Returns the application’s mutex service.
getPath()Returns the path service.
getPluginStore()Returns the plugin store service.
getPlugins()Returns the plugins service.
getProjectConfig()Returns the system config service.
getQueue()Returns the queue service.
getRelations()Returns the relations service.
getRequest()Returns the request component.
getResponse()Returns the response component.
getRoutes()Returns the routes service.
getRuntimePath()Returns the directory that stores runtime files.
getSearch()Returns the search service.
getSections()Returns the sections service.
getSecurity()Returns the security component.
getSession()Returns the session component.
getSites()Returns the sites service.
getStructures()Returns the structures service.
getSystemMessages()Returns the system email messages service.
getSystemName()Returns the system name.
getSystemSettings()Returns the system settings service.
getSystemUid()Returns the system's UID.
getTags()Returns the tags service.
getTargetLanguage()Returns the target app language.
getTemplateCaches()Returns the template cache service.
getTimeZone()Returns the time zone used by this application.
getTokens()Returns the tokens service.
getUniqueId()Returns an ID that uniquely identifies this module among all modules within the current application.
getUpdates()Returns the updates service.
getUrlManager()Returns the URL manager for this application.
getUser()Returns the user component.
getUserGroups()Returns the user groups service.
getUserPermissions()Returns the user permissions service.
getUsers()Returns the users service.
getUtilities()Returns the utilities service.
getVendorPath()Returns the directory that stores vendor files.
getVersion()Returns current module version.
getView()Returns the view object.
getViewPath()Returns the directory that contains the view files for this module.
getVolumes()Returns the volumes service.
getYiiVersion()Returns the Yii framework version.
handleRequest()Handles the specified request.
has()Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasModule()Checks whether the child module of the specified ID exists.
hasProperty()Returns a value indicating whether a property is defined.
init()Initializes the application.
off()Detaches an existing event handler from this component.
on()Attaches an event handler to an event.
preInit()Pre-initializes the application.
requireEdition()Requires that Craft is running an equal or better edition than what's passed in
run()Runs the application.
runAction()Runs a controller action specified by a route.
saveInfo()Updates the info row.
set()Registers a component definition with this locator.
setAliases()Defines path aliases.
setBasePath()Sets the root directory of the application and the @app alias.
setComponents()Registers a set of component definitions in this locator.
setContainer()Configures \craft\web\Yii::$container with the $config.
setEdition()Sets the Craft edition.
setHomeUrl()
setInstance()Sets the currently requested instance of this module class.
setIsInstalled()Sets Craft's record of whether it's installed
setLayoutPath()Sets the directory that contains the layout files.
setModule()Adds a sub-module to this module.
setModules()Registers sub-modules in the current module.
setRuntimePath()Sets the directory that stores runtime files.
setTimeZone()Sets the time zone used by this application.
setVendorPath()Sets the directory that stores vendor files.
setVersion()Sets current module version.
setViewPath()Sets the directory that contains the view files.
trigger()Triggers an event.
updateTargetLanguage()Sets the target application language.

__construct()

Constructor.

View source

Arguments

bootstrap()

Initializes extensions and executes bootstrap components.

This method is called by init() after the application has been fully configured. If you override this method, make sure you also call the parent implementation.

View source

get()

Returns the component instance with the specified ID.

Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module. The parent module may be the application.

View source

Arguments

  • $id (string) – Component ID (e.g. db).
  • $throwException (boolean) – Whether to throw an exception if $id is not registered with the locator before.

Returns

object, null – The component of the specified ID. If $throwException is false and $id is not registered before, null will be returned.

Throws

handleRequest()

Handles the specified request.

View source

Arguments

Returns

yii\web\Response – The resulting response

Throws

init()

Initializes the application.

View source

runAction()

Runs a controller action specified by a route.

This method parses the specified route and creates the corresponding child module(s), controller and action instances. It then calls craft\web\Controller::runAction() to run the action with the given parameters. If the route is empty, the method will use defaultRoute.

View source

Arguments

  • $route (string) – The route that specifies the action.
  • $params (array) – The parameters to be passed to the action

Returns

yii\web\Response, null – The result of the action, normalized into a Response object

Throws

setTimeZone()

Sets the time zone used by this application.

This is a simple wrapper of PHP function date_default_timezone_set(). Refer to the php manual for available timezones.

View source

Arguments

  • $value (string) – The time zone used by this application.

setVendorPath()

Sets the directory that stores vendor files.

View source

Arguments

  • $path (string) – The directory that stores vendor files.

Protected Methods

MethodDescription
debugBootstrap()Bootstraps the Debug Toolbar if necessary.
defaultVersion()Returns default module version.
ensureResourcePathExists()Ensures that the resources folder exists and is writable.
registerErrorHandler()Registers the errorHandler component as a PHP error handler.

debugBootstrap()

Bootstraps the Debug Toolbar if necessary.

View source

ensureResourcePathExists()

Ensures that the resources folder exists and is writable.

View source

Throws

Constants

ConstantDescription
STATE_AFTER_REQUESTApplication state used by state: application is triggering EVENT_AFTER_REQUEST.
STATE_BEFORE_REQUESTApplication state used by state: application is triggering EVENT_BEFORE_REQUEST.
STATE_BEGINApplication state used by state: application just started.
STATE_ENDApplication state used by state: application has ended.
STATE_HANDLING_REQUESTApplication state used by state: application is handling the request.
STATE_INITApplication state used by state: application is initializing.
STATE_SENDING_RESPONSEApplication state used by state: application is about to send response.

Events

EVENT_AFTER_EDITION_CHANGE

Type
craft\events\EditionChangeEvent

The event that is triggered after the edition changes

EVENT_INIT

Type
yii\base\Event

The event that is triggered after the application has been fully initialized

Example