Director
class Director implements TemplateGlobalProvider (View source)
Director is responsible for processing URLs, and providing environment information.
The most important part of director is {@link 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. |
Properties
static private array | $extensions | An array of extension names and parameters to be applied to this object upon construction. |
from Extensible |
static private array | $rules | ||
static private string | $alternate_base_folder | ||
static private bool|null | $alternate_public_dir | Override PUBLIC_DIR. Set to a non-null value to override. |
|
static private string | $default_base_url | Base url to populate if cannot be determined otherwise. |
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
Return the names of all the methods available on 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 {@link 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 {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link 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.
No description
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.
Returns indication whether the manifest cache has been flushed in the beginning of the current request.
Return the {@link 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 {@link 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
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.
Return the root-relative url for the baseurl
Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with {@link setBaseFolder()}.
Check if using a seperate public dir, and if so return this directory name.
Gets the webroot of the project, which may be a subfolder of {see 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 {@link 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 {@link is_relative_url()}, or if the host matches {@link 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.
Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the 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 {@link Director::isDev()}, {@link Director::isTest()}, and {@link Director::isLive()}.
This function will return true if the site is in a live environment. For information about environment types, see {@link Director::set_environment_type()}.
This function will return true if the site is in a development environment. For information about environment types, see {@link Director::set_environment_type()}.
This function will return true if the site is in a test environment. For information about environment types, see {@link 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
stat(string $name)
deprecated
deprecated
Get inherited config value
mixed
uninherited(string $name)
Gets the uninherited value for the given config option
$this
set_stat(string $name, mixed $value)
deprecated
deprecated
Update the config value for a given property
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 {@link Extensions}, {@link Object::createMethod()} or {@link Object::addWrapperMethod()}
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
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
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 {@link Object::$extensions} array. See {@link 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 {@link 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 {@link Object} instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through {@link singleton()} to avoid side-effects from stale extension information.
static array
get_extensions(string $class = null, bool $includeArgumentString = false)
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 {@link 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 {@link __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 {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link 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 {@link 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(array ...$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'); $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()
$this
setMiddlewares(HTTPMiddleware[] $middlewares)
$this
addMiddleware(HTTPMiddleware $middleware)
__construct()
static HTTPResponse
test(string $url, array $postVars = [], array|Session $session = array(), string $httpMethod = null, string $body = null, array $headers = array(), array|Cookie_Backend $cookies = array(), 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 bool
isManifestFlushed()
deprecated
deprecated
Returns indication whether the manifest cache has been flushed in the beginning of the current request.
That could mean the current active request has ?flush
parameter.
Another possibility is a race condition when the current request
hits the server in between another request ?flush
authorisation
and a redirect to the actual flush.
static SiteTree|Controller
get_current_page()
Return the {@link 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 {@link SiteTree} object that is being used to respond to the request.
static string
absoluteURL(string $url, string $relativeParent = self::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 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 {@link setBaseFolder()}.
static string
publicDir()
Check if using a seperate public dir, and if so return this directory name.
This will be removed in 5.0 and fixed to 'public'
static string
publicFolder()
Gets the webroot of the project, which may be a subfolder of {see 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 {@link 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 {@link 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 {@link is_relative_url()}, or if the host matches {@link 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.
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
forceSSL(array $patterns = null, string $secureDomain = null, HTTPRequest $request = null)
Force the site to run on SSL.
To use, call from the init() method of your PageController. 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 {@link Director::isDev()}, {@link Director::isTest()}, and {@link Director::isLive()}.
static bool
isLive()
This function will return true if the site is in a live environment. For information about environment types, see {@link 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 {@link 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 {@link 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.