Version: current

# Class RequestHandler

This class is the base class of any Sapphire object that can be used to handle HTTP requests.

Any RequestHandler object can be made responsible for handling its own segment of the URL namespace. The `Director` begins the URL parsing process; it will parse the beginning of the URL to identify which controller is being used. It will then call `RequestHandler::handleRequest()` on that Controller, passing it the parameters that it parsed from the URL, and the `SS_HTTPRequest` that contains the remainder of the URL to be parsed.

You can use ?debug_request=1 to view information about the different components and rule matches for a specific URL.

In Sapphire, URL parsing is distributed throughout the object graph. For example, suppose that we have a search form that contains a TreeMultiSelectField named "Groups". We want to use ajax to load segments of this tree as they are needed rather than downloading the tree right at the beginning. We could use this URL to get the tree segment that appears underneath Group #36: "admin/crm/SearchForm/field/Groups/treesegment/36" - Director will determine that admin/crm is controlled by a new ModelAdmin object, and pass control to that. Matching Director Rule: "admin/crm" => "ModelAdmin" (defined in mysite/_config.php) - ModelAdmin will determine that SearchForm is controlled by a Form object returned by $this->SearchForm(), and pass control to that. Matching $url_handlers: "$Action" => "$Action" (defined in RequestHandler class) - Form will determine that field/Groups is controlled by the Groups field, a TreeMultiselectField, and pass control to that. Matching $url_handlers: 'field/$FieldName!' => 'handleField' (defined in Form class) - TreeMultiselectField will determine that treesegment/36 is handled by its treesegment() method. This method will return an HTML fragment that is output to the screen. Matching $url_handlers: "$Action/$ID" => "handleItem" (defined in TreeMultiSelectField class)

`RequestHandler::handleRequest()` is where this behaviour is implemented.

  Object
  ViewableData implements IteratorAggregate
  RequestHandler

### Direct known subclasses

`CMSBatchActionHandler`, `Controller`, `Form`, `FormField`, `HtmlEditorField_Toolbar`, `PageCommentInterface`, `TableListField_ItemRequest`

### Indirect known subclasses

`AdvancedSearchForm`, `AjaxUniqueTextField`, `BookingAdminPage_Controller`, `GuestbookAdmin`, `GuestbookAdmin_CollectionController`, `HasManyComplexTableField`, `HasManyDataObjectManager`, `HasManyFileDataObjectManager`, `HasOneComplexTableField`, `HasOneDataObjectManager`, `HasOneFileDataObjectManager`, `HeaderField`, `HiddenField`, `BookingOrderAdmin`, `HomePage_Controller`, `HourlyTask`, `HouseCatalogSearchWidget_Controller`, `HTMLDropdownField`, `HtmlEditorField`, `HtmlEditorField_Readonly`, `ImageAssetManager`, `ImageDataObjectManager`, `ImageDataObjectManager_ItemRequest`, `ImageDataObjectManager_Popup`, `BookingOrderAdmin_CollectionController`, `ImageEditor`, `ImageField`, `ImageFormAction`, `Import1C_Controller`, `ImportCatalog1C_Controller`, `ImportCatalog1C_ProcessTask`, `ImportCatalog1C_ProductProp_Admin`, `InlineFormAction`, `InlineFormAction_ReadOnly`, `InstallerTest`, `BookingPage_Controller`, `JSTestRunner`, `LabelField`, `LanguageDropdownField`, `LastDoc_Controller`, `LeftAndMain`, `ListboxField`, `LiteralField`, `LiveCalendarWidget_Controller`, `LoggerAdmin`, `LoggerAdmin_CollectionController`, `BouncedList`, `LoggerAdmin_RecordController`, `LoginForm`, `LookupField`, `ManyManyComplexTableField`, `ManyManyDataObjectManager`, `ManyManyFileDataObjectManager`, `MapObject_Controller`, `MapObjectGroup_Controller`, `MapPage_Controller`, `Mediaweb3DPageFiles_Manager`, `Cart_Controller`, `MediawebForm`, `MediawebPage_Controller`, `MediawebPage_Popup`, `MediawebPageFiles_Manager`, `MediawebPagePhoto_Manager`, `MediawebPageTexture_Manager`, `Member_ProfileForm`, `MemberImportForm`, `MemberLoginForm`, `MemberTableField`, `CartPage_Controller`, `MemberTableField_ItemRequest`, `MemberTableField_Popup`, `ModelAdmin`, `ModelAdmin_CollectionController`, `ModelAdmin_RecordController`, `ModelAsController`, `ModelViewer`, `ModelViewer_Module`, `MoneyField`, `MonthlyTask`, `CartTableListField`, `Monument_Controller`, `Monument_PolishingTextField`, `MonumentAdmin`, `MonumentCatalog_Controller`, `MonumentForm_Controller`, `MultiUploadControls`, `MultiUploadField`, `MyRangeField`, `NewDocumentsAdmin`, `NewsArchive_Controller`, `Catalog_Controller`, `NewsEntry_Controller`, `NewsHolder_Controller`, `NewsletterAdmin`, `NewsletterList`, `NullableField`, `NumericField`, `OptionsetField`, `Order_CancelForm`, `OrderAdmin`, `OrderAdmin_CollectionController`, `CatalogAdmin`, `OrderAdmin_RecordController`, `OrderExporter`, `OrderItemField`, `Orders1CExchange_Controller`, `Page_Controller`, `PageComment_Controller`, `PageCommentInterface_Controller`, `PageCommentInterface_Form`, `PasswordField`, `Payment_Handler`, `Announcement_Controller`, `CatalogAdmin_CollectionController`, `PaymentAdmin`, `PaymentAdmin_CollectionController`, `PayPalPayment_Handler`, `PermissionCheckboxSetField`, `PermissionCheckboxSetField_Readonly`, `PhoneField`, `PhoneNumberField`, `PhotoAlbumManager`, `PhotoAlbumManager_Controller`, `PhotoAlbumManager_Popup`, `CatalogAdmin_RecordController`, `PhotoAlbumPage_Controller`, `PhotoGalleryPage_Controller`, `PhpCaptchaField`, `PollPage`, `PostVKNotificationQueueTask`, `PrintableTransformation_TabSet`, `Product_Controller`, `ProductCatalogImportTask`, `ProductImport1CAdmin`, `ProductImport1CAdmin_CollectionController`, `ChangePasswordForm`, `ProductImportAdmin`, `ProductImportAdmin_CollectionController`, `ProductParamValue_BoolValueField`, `ProductParamValue_MultiValueField`, `ProductParamValue_MultiValueSetField`, `ProductParamValue_ValueField`, `ProductSearchPage_Controller`, `ProfilePage_Controller`, `ProgressBar`, `PublHolder_Controller`, `CheckboxField`, `Publication_Controller`, `QuarterHourlyTask`, `QueuedEmailDispatchTask`, `RangeField`, `RatingExtension_Controller`, `ReadonlyField`, `RealtyImportAdmin`, `RealtyImportAdmin_CollectionController`, `RealtyXMLImportTask`, `RebuildStaticCacheTask`, `CheckboxField_Disabled`, `RecipientExportField`, `RecipientImportField`, `RecipientImportField_UploadForm`, `RedirectEntry_Admin`, `RedirectorPage_Controller`, `RegistrationPage_Controller`, `RemoveOrphanedPagesTask`, `ReportAdmin`, `ResetFormAction`, `RestfulServer`, `CheckboxField_Readonly`, `RestrictedTextField`, `RestrictionRegionCountryDropdownField`, `Room_Controller`, `RoomCatalog_Controller`, `RoomRate_PriceField`, `RoomServiceAdmin`, `RoomServiceDropdownField`, `RootURLController`, `SapphireInfo`, `SapphireREPL`, `CheckboxSetField`, `SapphireSoapServer`, `SberbankPayment_Handler`, `ScaffoldingComplexTableField_Popup`, `ScheduledTask`, `Search_Controller`, `SearchForm`, `Security`, `SecurityAdmin`, `SelectionGroup`, `ShippingMethodAdmin`, `CheckoutPage_Controller`, `ShippingMethodAdmin_CollectionController`, `ShowPoll`, `SimpleHTMLEditorField`, `SimpleImageField`, `SimpleImageField_Disabled`, `SimpleOrderForm_Controller`, `SimpleOrderPage_Controller`, `SimpleTinyMCEField`, `SimpleTreeDropdownField`, `SimpleWysiwygField`, `ChequePayment_Handler`, `SiteMap_Controller`, `SiteTreeMaintenanceTask`, `SOAPModelAccess`, `Socle_Controller`, `SocleSize_Controller`, `SocleSize_SocleSectionTextField`, `SpamProtectorField`, `SpecialCatalog_Controller`, `StartCatalog_Controller`, `StateDropdownField`, `CliController`, `StateProvinceDropdownField`, `StaticExporter`, `StealthFieldCaptcha`, `SubmittedFormReportField`, `SubpageListField`, `SubPageListField_ItemRequest`, `SubscribeForm_Controller`, `SubsiteAdmin`, `SubsiteAdmin_CollectionController`, `SubsiteAgnosticTableListField`, `AnnouncementHolder_Controller`, `CMSActionOptionsForm`, `SubsiteDropdownField`, `SubsitesSelectorPage_Controller`, `SubsitesTreeDropdownField`, `SubsitesVirtualPage_Controller`, `Tab`, `TableField`, `TableListField`, `TabSet`, `TaskRunner`, `TestRunner`, `CMSMain`, `TestViewer`, `TextareaField`, `TextField`, `TextFieldWithEmptyFlag`, `TextLiteralField`, `ThumbnailStripField`, `TimeField`, `TimeField_Readonly`, `ToggleCompositeField`, `ToggleField`, `CodeViewer`, `TreeDropdownField`, `TreeDropdownField_Readonly`, `TreeMultiselectField`, `TreeMultiselectField_Readonly`, `TreeSelectorField`, `UniqueRestrictedTextField`, `UniqueTextField`, `UnitellerPayment_Handler`, `Unsubscribe_Controller`, `Unsubscribe_MailingListForm`, `CommentAdmin`, `UnsubscribedList`, `Upload`, `UserDefinedForm_Controller`, `VAT_Admin`, `VersionedRestfulServer`, `VideoBankPage_Controller`, `VideoManager`, `VirtualPage_Controller`, `VirtualProduct_Controller`, `VKNotificationQueueAdmin`, `CommentTableField`, `WeeklyTask`, `Widget_Controller`, `Widget_TreeDropdownField`, `WidgetAdmin`, `WidgetAreaEditor`, `YaMoneyPayment_Handler`, `YearlyTask`, `YMLExporter`, `ComplexTableField`, `ComplexTableField_ItemRequest`, `ComplexTableField_Popup`, `CompositeField`, `ConfirmedPasswordField`, `AssetAdmin`, `ContactsPage_Controller`, `ContentController`, `CorrectBadFoldersTask`, `CountryDropdownField`, `CreditCardField`, `CurrencyField`, `CurrencyField_Disabled`, `CurrencyField_Readonly`, `CustomMenuAdmin`, `DailyTask`, `AssetManager`, `DashboardAdmin`, `DatabaseAdmin`, `DatalessField`, `DataObjectManager`, `DataObjectManager_Controller`, `DataObjectManager_ItemRequest`, `DataObjectManager_Popup`, `DateField`, `DateField_Disabled`, `DatePickerField`, `AssetTableField`, `DatePickerField_Controller`, `DatetimeField`, `DatetimeField_Readonly`, `DeleteEmptyAssociatedFoldersTask`, `DeleteUnconfirmTask`, `DevelopmentAdmin`, `DocPage_Controller`, `DocumentPageFiles_Manager`, `DocumentSearchForm`, `DocumentsPage_Controller`, `AutoCompleteField`, `DropdownField`, `Email_BounceHandler`, `EmailField`, `ErrorPage_Controller`, `Event_Controller`, `EventHolder_Controller`, `FaqAdmin`, `FaqHolder_Controller`, `FaqSection_Controller`, `FavoritePage_Controller`, `AutocompleteTextField`, `FieldEditor`, `FieldGroup`, `FileComplexTableField`, `FileDataObjectManager`, `FileDataObjectManager_Controller`, `FileDataObjectManager_ItemRequest`, `FileDataObjectManager_Popup`, `FileField`, `FileIFrameField`, `FileList`, `BatchProcess_Controller`, `FillTechTitleTask`, `FindCyrillic`, `FindCyrillic_Controller`, `Folder_UnusedAssetsField`, `FormAction`, `FormAction_WithoutLabel`, `GoogleSitemap`, `GroupedDropdownField`, `GroupImportForm`, `Guestbook_Controller`

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

## Methods summary

`public` | # `__construct( )` #### Overrides `Object::__construct`
`public `SS_HTTPResponse`|`RequestHandler`|string|array` | # `handleRequest( `SS_HTTPRequest` $request )` Handles URL requests. Handles URL requests. ViewableData::handleRequest() iterates through each rule in `RequestHandler::$url_handlers`. - If the rule matches, the named method will be called. - If there is still more URL to be processed, then handleRequest() is called on the object that that method returns. Once all of the URL has been processed, the final result is returned. However, if the final result is an array, this array is interpreted as being additional template data to customise the 2nd to last result with, rather than an object in its own right. This is most frequently used when a Controller's action will return an array of data with which to customise the controller. #### Parameters $request $request The `SS_HTTPRequest` object that is reponsible for distributing URL parsing #### Returns ``SS_HTTPResponse`|`RequestHandler`|string|array` SS_HTTPResponse|RequestHandler|string|array #### Uses ``SS_HTTPRequest`` ``SS_HTTPRequest::match()``
`public array|null` | # `allowedActions( )` Get a unified array of allowed actions on this controller (if such data is available) from both the controller ancestry and any extensions. Get a unified array of allowed actions on this controller (if such data is available) from both the controller ancestry and any extensions. #### Returns `array|null` array|null
`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
`public` | # `checkAccessAction( mixed $action )` Check that the given action is allowed to be called from a URL. It will interrogate `RequestHandler::$allowed_actions` to determine this. Check that the given action is allowed to be called from a URL. It will interrogate `RequestHandler::$allowed_actions` to determine this.
`public` | # `httpError( integer $errorCode, string $errorMessage = null )` Throws a HTTP error response encased in a `SS_HTTPResponse_Exception`, which is later caught in RequestHandler::handleAction() and returned to the user. Throws a HTTP error response encased in a `SS_HTTPResponse_Exception`, which is later caught in RequestHandler::handleAction() and returned to the user. #### Parameters $errorCode int $errorCode $errorMessage string $errorMessage #### Uses ``SS_HTTPResponse_Exception``
`public `SS_HTTPRequest`` | # `getRequest( )` Returns the SS_HTTPRequest object that this controller is using. Returns the SS_HTTPRequest object that this controller is using. #### Returns ``SS_HTTPRequest`` SS_HTTPRequest

### Methods inherited from ViewableData

`ATT_val()`, `BaseHref()`, `CSSClasses()`, `ColumnBreak()`, `ColumnCalc()`, `ColumnNumber()`, `ColumnPad()`, `ColumnPos()`, `CurrentMember()`, `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 mixed` | $request | #
`protected boolean` | $brokenOnConstruct | # This variable records whether RequestHandler::__construct() was called or not. Useful for checking if subclasses have called parent::__construct() This variable records whether RequestHandler::__construct() was called or not. Useful for checking if subclasses have called parent::__construct()
`public static array` | $url_handlers | # The default URL handling rules. This specifies that the next component of the URL corresponds to a method to be called on this RequestHandlingData object. The default URL handling rules. This specifies that the next component of the URL corresponds to a method to be called on this RequestHandlingData object. The keys of this array are parse rules. See `SS_HTTPRequest::match()` for a description of the rules available. The values of the array are the method to be called if the rule matches. If this value starts with a '$', then the named parameter of the parsed URL wil be used to determine the method name.
`public static mixed` | $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
    );

### 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. -