Version: current

# Class Controller

Base controller class. Controllers are the cornerstone of all site functionality in Sapphire. The `Director` selects a controller to pass control to, and then calls run(). This method will execute the appropriate action - either by calling the action method, or displaying the action's template.

See getTemplate() for information on how the template is chosen.

  Object
  ViewableData implements IteratorAggregate
  RequestHandler
  Controller

### Direct known subclasses

`BatchProcess_Controller`, `Cart_Controller`, `FileDataObjectManager_Controller`, `FindCyrillic_Controller`, `GoogleSitemap`, `ImageEditor`, `InstallerTest`, `JSTestRunner`, `LeftAndMain`, `LiveCalendarWidget_Controller`, `ModelAdmin_CollectionController`, `ModelAdmin_RecordController`, `CliController`, `ModelAsController`, `ModelViewer`, `MultiUploadControls`, `OrderExporter`, `PageComment_Controller`, `Payment_Handler`, `PhotoAlbumManager_Controller`, `RebuildStaticCacheTask`, `RemoveOrphanedPagesTask`, `RestfulServer`, `CodeViewer`, `RootURLController`, `SapphireInfo`, `SapphireREPL`, `SapphireSoapServer`, `Security`, `SiteTreeMaintenanceTask`, `StaticExporter`, `TaskRunner`, `TestRunner`, `TestViewer`, `ContentController`, `Upload`, `VersionedRestfulServer`, `Widget_Controller`, `YMLExporter`, `DatabaseAdmin`, `DataObjectManager_Controller`, `DatePickerField_Controller`, `DevelopmentAdmin`, `Email_BounceHandler`

### Indirect known subclasses

`Announcement_Controller`, `AnnouncementHolder_Controller`, `CatalogAdmin_CollectionController`, `SberbankPayment_Handler`, `ScheduledTask`, `Search_Controller`, `SecurityAdmin`, `ShippingMethodAdmin`, `ShippingMethodAdmin_CollectionController`, `SimpleOrderForm_Controller`, `SimpleOrderPage_Controller`, `SiteMap_Controller`, `SOAPModelAccess`, `CatalogAdmin_RecordController`, `Socle_Controller`, `SocleSize_Controller`, `SpecialCatalog_Controller`, `StartCatalog_Controller`, `SubscribeForm_Controller`, `SubsiteAdmin`, `SubsiteAdmin_CollectionController`, `SubsitesSelectorPage_Controller`, `SubsitesVirtualPage_Controller`, `UnitellerPayment_Handler`, `CheckoutPage_Controller`, `Unsubscribe_Controller`, `UserDefinedForm_Controller`, `VAT_Admin`, `VideoBankPage_Controller`, `VirtualPage_Controller`, `VirtualProduct_Controller`, `VKNotificationQueueAdmin`, `WeeklyTask`, `WidgetAdmin`, `YaMoneyPayment_Handler`, `ChequePayment_Handler`, `YearlyTask`, `CMSMain`, `CommentAdmin`, `ContactsPage_Controller`, `CorrectBadFoldersTask`, `CustomMenuAdmin`, `DailyTask`, `AssetAdmin`, `DashboardAdmin`, `DeleteEmptyAssociatedFoldersTask`, `DeleteUnconfirmTask`, `DocPage_Controller`, `DocumentsPage_Controller`, `ErrorPage_Controller`, `Event_Controller`, `EventHolder_Controller`, `FaqAdmin`, `FaqHolder_Controller`, `BookingAdminPage_Controller`, `FaqSection_Controller`, `FavoritePage_Controller`, `FillTechTitleTask`, `FindCyrillic`, `Guestbook_Controller`, `GuestbookAdmin`, `GuestbookAdmin_CollectionController`, `HomePage_Controller`, `HourlyTask`, `HouseCatalogSearchWidget_Controller`, `BookingOrderAdmin`, `Import1C_Controller`, `ImportCatalog1C_Controller`, `ImportCatalog1C_ProcessTask`, `ImportCatalog1C_ProductProp_Admin`, `LastDoc_Controller`, `LoggerAdmin`, `LoggerAdmin_CollectionController`, `LoggerAdmin_RecordController`, `MapObject_Controller`, `MapObjectGroup_Controller`, `BookingOrderAdmin_CollectionController`, `MapPage_Controller`, `MediawebPage_Controller`, `ModelAdmin`, `ModelViewer_Module`, `MonthlyTask`, `Monument_Controller`, `MonumentAdmin`, `MonumentCatalog_Controller`, `MonumentForm_Controller`, `NewDocumentsAdmin`, `BookingPage_Controller`, `NewsArchive_Controller`, `NewsEntry_Controller`, `NewsHolder_Controller`, `NewsletterAdmin`, `OrderAdmin`, `OrderAdmin_CollectionController`, `OrderAdmin_RecordController`, `Orders1CExchange_Controller`, `Page_Controller`, `PageCommentInterface_Controller`, `CartPage_Controller`, `PaymentAdmin`, `PaymentAdmin_CollectionController`, `PayPalPayment_Handler`, `PhotoAlbumPage_Controller`, `PhotoGalleryPage_Controller`, `PollPage`, `PostVKNotificationQueueTask`, `Product_Controller`, `ProductCatalogImportTask`, `ProductImport1CAdmin`, `Catalog_Controller`, `ProductImport1CAdmin_CollectionController`, `ProductImportAdmin`, `ProductImportAdmin_CollectionController`, `ProductSearchPage_Controller`, `ProfilePage_Controller`, `PublHolder_Controller`, `Publication_Controller`, `QuarterHourlyTask`, `QueuedEmailDispatchTask`, `RatingExtension_Controller`, `CatalogAdmin`, `RealtyImportAdmin`, `RealtyImportAdmin_CollectionController`, `RealtyXMLImportTask`, `RedirectEntry_Admin`, `RedirectorPage_Controller`, `RegistrationPage_Controller`, `ReportAdmin`, `Room_Controller`, `RoomCatalog_Controller`, `RoomServiceAdmin`

Package: sapphire\control
Located at sapphire/core/control/Controller.php

## Methods summary

`public` | # `init( )` Initialisation function that is run before any action on the controller is called. Initialisation function that is run before any action on the controller is called. #### Uses ``BasicAuth::requireLogin()``
`public `SS_HTTPResponse`` | # `handleRequest( `SS_HTTPRequest` $request )` Executes this controller, and return an `SS_HTTPResponse` object with the result. Executes this controller, and return an `SS_HTTPResponse` object with the result. This method first does a few set-up activities: - Push this controller ont to the controller stack - see `Controller::curr()` for information about this. - Call `Controller::init()` - Defer to RequestHandler->handleRequest() to determine which action should be executed Note: $requestParams['executeForm'] support was removed, make the following change in your URLs: "/?executeForm=FooBar" -> "/FooBar" Also make sure "FooBar" is in the $allowed_actions of your controller class. Note: You should rarely need to overload run() - this kind of change is only really appropriate for things like nested controllers - `ModelAsController` and `RootURLController` are two examples here. If you want to make more orthodox functionality, it's better to overload `Controller::init()` or index(). Important: If you are going to overload handleRequest, make sure that you start the method with $this->pushCurrent() and end the method with $this->popCurrent(). Failure to do this will create weird session errors. #### Parameters $request $request The `SS_HTTPRequest` object that is responsible for distributing request parsing. #### Returns ``SS_HTTPResponse`` The response that this controller produces, including HTTP headers such as redirection info #### Overrides `RequestHandler::handleRequest`
`public` | # `handleAction( mixed $request )` Controller's default action handler. It will call the method named in $Action, if that method exists. If $Action isn't given, it will use "index" as a default. Controller's default action handler. It will call the method named in $Action, if that method exists. If $Action isn't given, it will use "index" as a default.
`public` | # `setURLParams( mixed $urlParams )`
`public array` | # `getURLParams( )` #### Returns `array` The parameters extracted from the URL by the `Director`.
`public` | # `getResponse( )` Returns the SS_HTTPResponse object that this controller is building up. Can be used to set the status code and headers Returns the SS_HTTPResponse object that this controller is building up. Can be used to set the status code and headers
`public `SS_HTTPRequest`` | # `getRequest( )` Get the request with which this controller was called (if any). Usually set in `Controller::handleRequest()`. Get the request with which this controller was called (if any). Usually set in `Controller::handleRequest()`. #### Returns ``SS_HTTPRequest`` SS_HTTPRequest #### Overrides `RequestHandler::getRequest`
`public` | # `getFormOwner( )` Return the object that is going to own a form that's being processed, and handle its execution. Note that the result needn't be an actual controller object. Return the object that is going to own a form that's being processed, and handle its execution. Note that the result needn't be an actual controller object.
`public` | # `defaultAction( mixed $action )` This is the default action handler used if a method doesn't exist. It will process the controller object with the template returned by `Controller::getViewer()` This is the default action handler used if a method doesn't exist. It will process the controller object with the template returned by `Controller::getViewer()`
`public` | # `getAction( )` Returns the action that is being executed on this controller. Returns the action that is being executed on this controller.
`public `SSViewer`` | # `getViewer( mixed $action )` Return an SSViewer object to process the data Return an SSViewer object to process the data #### Returns ``SSViewer`` The viewer identified being the default handler for this Controller/Action combination
`public boolean` | # `hasAction( string $action )` Checks if this request handler has a specific action (even if the current user cannot access it). Checks if this request handler has a specific action (even if the current user cannot access it). #### Parameters $action string $action #### Returns `boolean` bool #### Overrides `RequestHandler::hasAction`
`public boolean` | # `hasActionTemplate( string $action )` Returns TRUE if this controller has a template that is specifically designed to handle a specific action. Returns TRUE if this controller has a template that is specifically designed to handle a specific action. #### Parameters $action string $action #### Returns `boolean` bool
`public string` | # `render( array $params = null )` Render the current controller with the templates determined by `Controller::getViewer()`. Render the current controller with the templates determined by `Controller::getViewer()`. #### Parameters $params array $params Key-value array for custom template variables (Optional) #### Returns `string` Parsed template content
`public` | # `disableBasicAuth( )` Call this to disable site-wide basic authentication for a specific contoller. This must be called before Controller::init(). That is, you must call it in your controller's init method before it calls parent::init(). Call this to disable site-wide basic authentication for a specific contoller. This must be called before Controller::init(). That is, you must call it in your controller's init method before it calls parent::init().
`public static` | # `curr( )` Returns the current controller Returns the current controller #### Returns Controller
`public static boolean` | # `has_curr( )` Tests whether we have a currently active controller or not Tests whether we have a currently active controller or not #### Returns `boolean` True if there is at least 1 controller in the stack.
`public boolean` | # `can( perm $perm, member $member = null )` Returns true if the member is allowed to do the given action. Returns true if the member is allowed to do the given action. #### Parameters $perm perm The permission to be checked, such as 'View'. $member member The member whose permissions need checking. Defaults to the currently logged in user. #### Returns `boolean` boolean
`public `Date`` | # `Now( )` returns a date object for use within a template Usage: $Now.Year - Returns 2006 returns a date object for use within a template Usage: $Now.Year - Returns 2006 #### Returns ``Date`` The current date
`public` | # `CurrentMember( )` Returns the currently logged in user Returns the currently logged in user #### Overrides `ViewableData::CurrentMember`
`public boolean` | # `PastVisitor( )` Returns true if the visitor has been here before Returns true if the visitor has been here before #### Returns `boolean` boolean
`public boolean` | # `PastMember( )` Return true if the visitor has signed up for a login account before Return true if the visitor has signed up for a login account before #### Returns `boolean` boolean
`public` | # `pushCurrent( )` Pushes this controller onto the stack of current controllers. This means that any redirection, session setting, or other things that rely on Controller::curr() will now write to this controller object. Pushes this controller onto the stack of current controllers. This means that any redirection, session setting, or other things that rely on Controller::curr() will now write to this controller object.
`public` | # `popCurrent( )` Pop this controller off the top of the stack. Pop this controller off the top of the stack.
`public` | # `redirect( mixed $url, mixed $code = 302 )` Redirct to the given URL. It is generally recommended to call Director::redirect() rather than calling this function directly. Redirct to the given URL. It is generally recommended to call Director::redirect() rather than calling this function directly. #### Used by ``Controller::redirectBack()``
`public` | # `redirectBack( )` Redirect back. Uses either the HTTP_REFERER or a manually set request-variable called _REDIRECT_BACK_URL. This variable is needed in scenarios where not HTTP-Referer is sent ( e.g when calling a page by location.href in IE). If none of the two variables is available, it will redirect to the base URL (see `Director::baseURL()`). Redirect back. Uses either the HTTP_REFERER or a manually set request-variable called _REDIRECT_BACK_URL. This variable is needed in scenarios where not HTTP-Referer is sent ( e.g when calling a page by location.href in IE). If none of the two variables is available, it will redirect to the base URL (see `Director::baseURL()`). #### Uses ``Controller::redirect()``
`public string` | # `redirectedTo( )` Tests whether a redirection has been requested. Tests whether a redirection has been requested. #### Returns `string` If redirect() has been called, it will return the URL redirected to. Otherwise, it will return null;
`public `Session`` | # `getSession( )` Get the Session object representing this Controller's session Get the Session object representing this Controller's session #### Returns ``Session`` Session
`public` | # `setSession( `Session` $session )` Set the Session object. Set the Session object.
`public boolean` | # `isAjax( )` Returns true if this controller is processing an ajax request Returns true if this controller is processing an ajax request #### Returns `boolean` True if this controller is processing an ajax request
`public static String` | # `join_links( )` Joins two or more link segments together, putting a slash between them if necessary. Use this for building the results of Link() methods. If either of the links have query strings, then they will be combined and put at the end of the resulting url. Joins two or more link segments together, putting a slash between them if necessary. Use this for building the results of Link() methods. If either of the links have query strings, then they will be combined and put at the end of the resulting url. Caution: All parameters are expected to be URI-encoded already. #### Returns `String` String

### Methods inherited from RequestHandler

`__construct()`, `allowedActions()`, `checkAccessAction()`, `httpError()`

### Methods inherited from ViewableData

`ATT_val()`, `BaseHref()`, `CSSClasses()`, `ColumnBreak()`, `ColumnCalc()`, `ColumnNumber()`, `ColumnPad()`, `ColumnPos()`, `CurrentPage()`, `Debug()`, `Even()`, `EvenOdd()`, `First()`, `FirstLast()`, `HasPerm()`, `IsAjax()`, `JS_val()`, `Last()`, `Me()`, `Middle()`, `MiddleString()`, `Modulus()`, `MultipleOf()`, `Odd()`, `Pos()`, `RAW_val()`, `SQL_val()`, `ThemeDir()`, `ThemeName()`, `Top()`, `TotalItems()`, `XML_val()`, `__get()`, `__isset()`, `__set()`, `buildCastingCache()`, `cachedCall()`, `castingClass()`, `castingHelper()`, `castingHelperPair()`, `castingObjectCreator()`, `castingObjectCreatorPair()`, `customise()`, `defineMethods()`, `escapeTypeForField()`, `getField()`, `getIterator()`, `getSecurityID()`, `getXMLValues()`, `hasField()`, `hasValue()`, `i18nLocale()`, `iteratorProperties()`, `obj()`, `renderWith()`, `setCustomisedObj()`, `setField()`

### Methods inherited from Object

`__call()`, `__toString()`, `__wakeup()`, `addMethodsFrom()`, `addStaticVars()`, `addWrapperMethod()`, `add_extension()`, `add_static_var()`, `allMethodNames()`, `cacheToFile()`, `cacheToFileWithArgs()`, `clearCache()`, `combined_static()`, `create()`, `createMethod()`, `create_from_string()`, `exists()`, `extInstance()`, `extend()`, `getCustomClass()`, `getExtensionInstance()`, `getExtensionInstances()`, `get_extensions()`, `get_static()`, `hasExtension()`, `hasMethod()`, `has_extension()`, `invokeWithExtensions()`, `is_a()`, `loadCache()`, `parentClass()`, `parse_class_spec()`, `remove_extension()`, `sanitiseCachename()`, `saveCache()`, `set_stat()`, `set_static()`, `set_uninherited()`, `stat()`, `strong_create()`, `uninherited()`, `uninherited_static()`, `useCustomClass()`

### Magic methods summary

## Properties summary

`protected array` | $urlParams | # $urlParams An array of arguments extracted from the URL $urlParams An array of arguments extracted from the URL
`protected array` | $requestParams | # $requestParams Contains all GET and POST parameters passed to the current `SS_HTTPRequest`. $requestParams Contains all GET and POST parameters passed to the current `SS_HTTPRequest`. #### Uses ``SS_HTTPRequest::requestVars()``
`protected string` | $action | # $action The URL part matched on the current controller as determined by the "$Action" part of the `Controller::$url_handlers` definition. Should correlate to a public method on this controller. Used in `Controller::render()` and `Controller::getViewer()` to determine action-specific templates. $action The URL part matched on the current controller as determined by the "$Action" part of the `Controller::$url_handlers` definition. Should correlate to a public method on this controller. Used in `Controller::render()` and `Controller::getViewer()` to determine action-specific templates.
`protected mixed` | $session | # The `Session` object for this controller The `Session` object for this controller
`protected static array` | $controller_stack | # Stack of current controllers. Controller::$controller_stack[0] is the current controller. Stack of current controllers. Controller::$controller_stack[0] is the current controller.
`protected boolean` | $basicAuthEnabled | #
`protected `SS_HTTPResponse`` | $response | # $response The response object that the controller returns. Set in `Controller::handleRequest()`. $response The response object that the controller returns. Set in `Controller::handleRequest()`.
`protected `SS_HTTPRequest`` | $request | # $request The request object that the controller was called with. Set in `Controller::handleRequest()`. Useful to generate the {} $request The request object that the controller was called with. Set in `Controller::handleRequest()`. Useful to generate the {}
`public static array` | $url_handlers | # Default URL handlers - (Action)/(ID)/(OtherID) Default URL handlers - (Action)/(ID)/(OtherID)
`public static array` | $allowed_actions | # Define a list of action handling methods that are allowed to be called directly by URLs. The variable should be an array of action names. This sample shows the different values that it can contain: Define a list of action handling methods that are allowed to be called directly by URLs. The variable should be an array of action names. This sample shows the different values that it can contain:
    array(
            'someaction', // someaction can be accessed by anyone, any time
            'otheraction' => true, // So can otheraction
            'restrictedaction' => 'ADMIN', // restrictedaction can only be people with ADMIN privilege
            'complexaction' '->canComplexAction' // complexaction can only be accessed if $this->canComplexAction() returns true
    );
`protected boolean` | $baseInitCalled | #

### Properties inherited from RequestHandler

`$brokenOnConstruct`

### Properties inherited from ViewableData

`$casting`, `$customisedObject`, `$default_cast`, `$failover`, `$iteratorPos`, `$iteratorTotalItems`

### Properties inherited from Object

`$class`, `$extension_instances`, `$extensions`

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -