Director
class Director implements TemplateGlobalProvider (View source)
Director is responsible for processing URLs, and providing environment information.
The most important part of director is Director::handleRequest(), which is passed an HTTPRequest and will execute the appropriate controller.
Traits
Provides extensions to this object to integrate it with standard config API methods.
Allows an object to have extensions applied to it.
A class that can be instantiated or replaced via DI
Adds middleware support to an object.
Allows an object to declare a set of custom methods
Constants
BASE |
Specifies this url is relative to the base. |
ROOT |
Specifies this url is relative to the site root. |
REQUEST |
specifies this url is relative to the current request. |
Config options
extensions | array | An array of extension names and parameters to be applied to this object upon construction. |
from Extensible |
unextendable_classes | array | Classes that cannot be extended |
from Extensible |
rules | array | ||
alternate_base_folder | string | ||
default_base_url | string | Base url to populate if cannot be determined otherwise. |
Properties
protected static | array | $extra_methods | Custom method sources |
from CustomMethods |
protected | array | $extra_method_registers | Name of methods to invoke by defineMethods for this instance |
from CustomMethods |
protected static | array | $built_in_methods | Non-custom public methods. |
from CustomMethods |
protected | Extension[] | $extension_instances | from Extensible | |
protected | callable[][] | $beforeExtendCallbacks | List of callbacks to call prior to extensions having extend called on them, each grouped by methodName. |
from Extensible |
protected | callable[][] | $afterExtendCallbacks | List of callbacks to call after extensions having extend called on them, each grouped by methodName. |
from Extensible |
protected | HTTPMiddleware[] | $middlewares | from HTTPMiddlewareAware |
Methods
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
Gets the uninherited value for the given config option
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
Adds any methods from Extension instances attached to this object.
Register an callback to invoke that defines extra methods
Return TRUE if a method exists on this object
Determines if a custom method with this name is defined.
Get meta-data details on a named method
Return the names of all the methods available on this object
Get all public built in methods for this class
Find all methods on the given object.
Add all the methods from an object property.
Add all the methods from an object property (which is an Extension) to this object.
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
Add callback as a method.
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
Adds any methods from Extension instances attached to this object.
Add an extension to a specific class.
No description
Get extra config sources for this class
Return TRUE if a class has a specified extension.
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Get an extension instance attached to this object by name.
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Get all extension instances for this specific object instance.
An implementation of the factory method, allows you to create an instance of a class
Creates a class instance by the "singleton" design pattern.
Test a URL request, returning a response object. This method is a wrapper around Director::handleRequest() to assist with functional testing. It will execute the URL given, and return the result as an HTTPResponse object.
Mock a request, passing this to the given callback, before resetting.
Process the given URL, creating the appropriate controller and executing it.
Return the SiteTree object that is currently being viewed. If there is no SiteTree object to return, then this will return the current controller.
Set the currently active SiteTree object that is being used to respond to the request.
Converts the given path or url into an absolute url. This method follows the below rules:
- Absolute urls (e.g.
http://localhost
) are not modified - Relative urls (e.g.
//localhost
) have current protocol added (http://localhost
) - Absolute paths (e.g.
/base/about-us
) are resolved by adding the current protocol and host (http://localhost/base/about-us
) - Relative paths (e.g.
about-us/staff
) must be resolved using one of three methods, disambiguated via the $relativeParent argument:- BASE - Append this path to the base url (i.e. behaves as though
<base>
tag is provided in a html document). This is the default.
- BASE - Append this path to the base url (i.e. behaves as though
Return only host (and optional port) part of a url
Validate user and password in URL, disallowing slashes
A helper to determine the current hostname used to access the site.
Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment variable isn't set.
Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with setBaseFolder().
Gets the webroot of the project, which may be a subfolder of {baseFolder()}
Turns an absolute URL or folder into one that's relative to the root of the site. This is useful when turning a URL into a filesystem reference, or vice versa.
Returns true if a given path is absolute. Works under both *nix and windows systems.
Determine if the url is root relative (i.e. starts with /, but not with //) SilverStripe considers root relative urls as a subset of relative urls.
Checks if a given URL is absolute (e.g. starts with 'http://' etc.). URLs beginning with "//" are treated as absolute, as browsers take this to mean the same protocol as currently being used.
Checks if a given URL is relative (or root relative) by checking is_absolute_url().
Checks if the given URL is belonging to this "site" (not an external link). That's the case if the URL is relative, as defined by is_relative_url(), or if the host matches protocolAndHost().
Given a filesystem reference relative to the site root, return the full file-system path.
Returns true if the given file exists. Filename should be relative to the site root.
Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL.
Skip any further processing and immediately respond with a redirect to the passed URL.
Force the site to run on SSL.
Checks if the current HTTP-Request is an "Ajax-Request" by checking for a custom header set by jQuery or whether a manually set request-parameter 'ajax' is present.
Returns true if this script is being run from the command line rather than the web server.
Can also be checked with Director::isDev()}, {@link Director::isTest(), and Director::isLive().
This function will return true if the site is in a live environment. For information about environment types, see Director::set_environment_type().
This function will return true if the site is in a development environment. For information about environment types, see Director::set_environment_type().
This function will return true if the site is in a test environment. For information about environment types, see Director::set_environment_type().
Returns an array of strings of the method names of methods on the call that should be exposed as global variables in the templates.
Details
static Config_ForClass
config()
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
mixed
uninherited(string $name)
Gets the uninherited value for the given config option
mixed
__call(string $method, array $arguments)
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
You can add extra methods to a class using Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()
protected
defineMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
protected
registerExtraMethodCallback(string $name, callable $callback)
Register an callback to invoke that defines extra methods
bool
hasMethod(string $method)
Return TRUE if a method exists on this object
This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions
protected bool
hasCustomMethod($method)
Determines if a custom method with this name is defined.
protected array
getExtraMethodConfig(string $method)
Get meta-data details on a named method
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
static protected array
findBuiltInMethods(string|object $class = null)
Get all public built in methods for this class
protected array
findMethodsFrom(object $object)
Find all methods on the given object.
protected
addMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property.
protected
removeMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property (which is an Extension) to this object.
protected
addWrapperMethod(string $method, string $wrap)
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
protected
addCallbackMethod(string $method, callable $callback)
Add callback as a method.
protected
beforeExtending(string $method, callable $callback)
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
protected
afterExtending(string $method, callable $callback)
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
protected
defineExtensionMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
static bool
add_extension(string $classOrExtension, string $extension = null)
Add an extension to a specific class.
The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.
As an alternative, extensions can be added to a specific class directly in the Object::$extensions array. See SiteTree::$extensions for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through singleton()).
static
remove_extension(string $extension)
Remove an extension from a class.
Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.
Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.
static array
get_extensions(string $class = null, bool $includeArgumentString = false)
No description
static array|null
get_extra_config_sources(string $class = null)
Get extra config sources for this class
static bool
has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)
Return TRUE if a class has a specified extension.
This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))
array
invokeWithExtensions(string $method, mixed ...$arguments)
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
array
extend(string $method, mixed ...$arguments)
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.
The extension methods are defined during __construct()} in {@link defineMethods().
Extension|null
getExtensionInstance(string $extension)
Get an extension instance attached to this object by name.
bool
hasExtension(string $extension)
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Caution: Don't use singleton(
Extension[]
getExtensionInstances()
Get all extension instances for this specific object instance.
See get_extensions() to get all applied extension classes for this class (not the instance).
This method also provides lazy-population of the extension_instances property.
static Injectable
create(mixed ...$args)
An implementation of the factory method, allows you to create an instance of a class
This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.
This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create(SiteTree::class); $list = SiteTree::get();
static Injectable
singleton(string $class = null)
Creates a class instance by the "singleton" design pattern.
It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).
HTTPMiddleware[]
getMiddlewares()
No description
$this
setMiddlewares(HTTPMiddleware[] $middlewares)
No description
$this
addMiddleware(HTTPMiddleware $middleware)
No description
protected HTTPResponse
callMiddleware(HTTPRequest $request, callable $last)
Call middleware
__construct()
No description
static HTTPResponse
test(string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)
Test a URL request, returning a response object. This method is a wrapper around Director::handleRequest() to assist with functional testing. It will execute the URL given, and return the result as an HTTPResponse object.
static mixed
mockRequest(callable $callback, string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)
Mock a request, passing this to the given callback, before resetting.
HTTPResponse
handleRequest(HTTPRequest $request)
Process the given URL, creating the appropriate controller and executing it.
Request processing is handled as follows:
- Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this request.
- Controller::handleRequest($request) is then called. This will find a rule to handle the URL, and call the rule handling method.
- RequestHandler::handleRequest($request) is recursively called whenever a rule handling method returns a RequestHandler object.
In addition to request processing, Director will manage the session, and perform the output of the actual response to the browser.
static SiteTree|Controller
get_current_page()
Return the SiteTree object that is currently being viewed. If there is no SiteTree object to return, then this will return the current controller.
static
set_current_page(SiteTree $page)
Set the currently active SiteTree object that is being used to respond to the request.
static string|bool
absoluteURL(string $url, string $relativeParent = Director::BASE)
Converts the given path or url into an absolute url. This method follows the below rules:
- Absolute urls (e.g.
http://localhost
) are not modified - Relative urls (e.g.
//localhost
) have current protocol added (http://localhost
) - Absolute paths (e.g.
/base/about-us
) are resolved by adding the current protocol and host (http://localhost/base/about-us
) - Relative paths (e.g.
about-us/staff
) must be resolved using one of three methods, disambiguated via the $relativeParent argument:- BASE - Append this path to the base url (i.e. behaves as though
<base>
tag is provided in a html document). This is the default.
- BASE - Append this path to the base url (i.e. behaves as though
- REQUEST - Resolve this path to the current url (i.e. behaves as though no
<base>
tag is provided in a html document) - ROOT - Treat this as though it was an absolute path, and append it to the protocol and hostname.
static protected string|null
parseHost(string $url)
Return only host (and optional port) part of a url
static protected bool
validateUserAndPass(string $url)
Validate user and password in URL, disallowing slashes
static string
host(HTTPRequest $request = null)
A helper to determine the current hostname used to access the site.
The following are used to determine the host (in order)
- Director.alternate_base_url (if it contains a domain name)
- Trusted proxy headers
- HTTP Host header
- SS_BASE_URL env var
- SERVER_NAME
- gethostname()
static int|null
port(HTTPRequest $request = null)
Return port used for the base URL.
Note, this will be null if not specified, in which case you should assume the default port for the current protocol.
static string|null
hostName(HTTPRequest $request = null)
Return host name without port
static bool|string
protocolAndHost(HTTPRequest $request = null)
Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment variable isn't set.
static string
protocol(HTTPRequest $request = null)
Return the current protocol that the site is running under.
static bool
is_https(HTTPRequest $request = null)
Return whether the site is running as under HTTPS.
static string
baseURL()
Return the root-relative url for the baseurl
static string
baseFolder()
Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with setBaseFolder().
static string
publicDir()
The name of the public directory
static string
publicFolder()
Gets the webroot of the project, which may be a subfolder of {baseFolder()}
static string
makeRelative(string $url)
Turns an absolute URL or folder into one that's relative to the root of the site. This is useful when turning a URL into a filesystem reference, or vice versa.
Note: You should check Director::is_site_url() if making an untrusted url relative prior to calling this function.
static bool
is_absolute(string $path)
Returns true if a given path is absolute. Works under both *nix and windows systems.
static bool
is_root_relative_url(string $url)
Determine if the url is root relative (i.e. starts with /, but not with //) SilverStripe considers root relative urls as a subset of relative urls.
static bool
is_absolute_url(string $url)
Checks if a given URL is absolute (e.g. starts with 'http://' etc.). URLs beginning with "//" are treated as absolute, as browsers take this to mean the same protocol as currently being used.
Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST, and avoid phishing attacks by redirecting to an attackers server.
Note: Can't solely rely on PHP's parse_url() , since it is not intended to work with relative URLs or for security purposes. filter_var($url, FILTER_VALIDATE_URL) has similar problems.
static bool
is_relative_url(string $url)
Checks if a given URL is relative (or root relative) by checking is_absolute_url().
static bool
is_site_url(string $url)
Checks if the given URL is belonging to this "site" (not an external link). That's the case if the URL is relative, as defined by is_relative_url(), or if the host matches protocolAndHost().
Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST, and avoid phishing attacks by redirecting to an attackers server.
Provides an extension point to allow extra checks on the URL to allow some external URLs, e.g. links on secondary domains that point to the same CMS, or subsite domains.
static string
getAbsFile(string $file)
Given a filesystem reference relative to the site root, return the full file-system path.
static bool
fileExists($file)
Returns true if the given file exists. Filename should be relative to the site root.
static string
absoluteBaseURL()
Returns the Absolute URL of the site root.
static string
absoluteBaseURLWithAuth(HTTPRequest $request = null)
Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL.
static protected
force_redirect(string $destURL)
Skip any further processing and immediately respond with a redirect to the passed URL.
static
forceSSL(array $patterns = null, string $secureDomain = null, HTTPRequest $request = null)
Force the site to run on SSL.
To use, call from _config.php. For example:
if (Director::isLive()) Director::forceSSL();
If you don't want your entire site to be on SSL, you can pass an array of PCRE regular expression patterns for matching relative URLs. For example:
if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'));
If you want certain parts of your site protected under a different domain, you can specify the domain as an argument:
if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'), 'secure.mysite.com');
Note that the session data will be lost when moving from HTTP to HTTPS. It is your responsibility to ensure that this won't cause usability problems.
CAUTION: This does not respect the site environment mode. You should check this as per the above examples using Director::isLive() or Director::isTest() for example.
static
forceWWW(HTTPRequest $request = null)
Force a redirect to a domain starting with "www."
static bool
is_ajax(HTTPRequest $request = null)
Checks if the current HTTP-Request is an "Ajax-Request" by checking for a custom header set by jQuery or whether a manually set request-parameter 'ajax' is present.
Note that if you plan to use this to alter your HTTP response on a cached page, you should add X-Requested-With to the Vary header.
static bool
is_cli()
Returns true if this script is being run from the command line rather than the web server.
static string
get_environment_type()
Can also be checked with Director::isDev()}, {@link Director::isTest(), and Director::isLive().
static bool
isLive()
This function will return true if the site is in a live environment. For information about environment types, see Director::set_environment_type().
static bool
isDev()
This function will return true if the site is in a development environment. For information about environment types, see Director::set_environment_type().
static bool
isTest()
This function will return true if the site is in a test environment. For information about environment types, see Director::set_environment_type().
static array
get_template_global_variables()
Returns an array of strings of the method names of methods on the call that should be exposed as global variables in the templates.
static protected HTTPRequest
currentRequest(HTTPRequest $request = null)
Helper to validate or check the current request object