Director
class Director implements TemplateGlobalProvider
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
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
rules | array | ||
alternate_base_folder | string | ||
alternate_public_dir | bool|null | Override PUBLIC_DIR. Set to a non-null value to override. | |
default_base_url | string | 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.
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
in Configurable at line 20
static Config_ForClass
config()
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .
....).
in Configurable at line 32
mixed
stat(string $name)
deprecated
deprecated 5.0 Use ->config()->get() instead
Get inherited config value
in Configurable at line 44
mixed
uninherited(string $name)
Gets the uninherited value for the given config option
in Configurable at line 57
$this
set_stat(string $name, mixed $value)
deprecated
deprecated 5.0 Use ->config()->set() instead
Update the config value for a given property
in CustomMethods at line 50
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()}
in CustomMethods at line 144
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
in CustomMethods at line 172
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
in Extensible at line 163
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()}).
in Extensible at line 224
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.
in Extensible at line 264
static array
get_extensions(string $class = null, bool $includeArgumentString = false)
in Extensible at line 298
static array|null
get_extra_config_sources(string $class = null)
Get extra config sources for this class
in Extensible at line 359
static bool
has_extension(string $classOrExtension, string $requiredExtension = null, boolean $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))
in Extensible at line 395
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
in Extensible at line 424
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()}.
in Extensible at line 465
Extension|null
getExtensionInstance(string $extension)
Get an extension instance attached to this object by name.
in Extensible at line 494
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(
in Extensible at line 508
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.
in Injectable at line 26
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();
in Injectable at line 43
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).
in HTTPMiddlewareAware at line 22
HTTPMiddleware[]
getMiddlewares()
in HTTPMiddlewareAware at line 31
$this
setMiddlewares(HTTPMiddleware[] $middlewares)
in HTTPMiddlewareAware at line 42
$this
addMiddleware(HTTPMiddleware $middleware)
at line 97
__construct()
at line 122
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.
at line 164
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.
at line 306
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.
at line 391
static bool
isManifestFlushed()
deprecated
deprecated 5.0 Kernel::isFlushed to be used instead
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.
at line 411
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.
at line 421
static
set_current_page(SiteTree $page)
Set the currently active {@link SiteTree} object that is being used to respond to the request.
at line 440
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.
- 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.
at line 538
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()
at line 580
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.
at line 592
static string|null
hostName(HTTPRequest $request = null)
Return host name without port
at line 605
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.
at line 616
static string
protocol(HTTPRequest $request = null)
Return the current protocol that the site is running under.
at line 627
static bool
is_https(HTTPRequest $request = null)
Return whether the site is running as under HTTPS.
at line 661
static string
baseURL()
Return the root-relative url for the baseurl
at line 688
static string
baseFolder()
Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with {@link setBaseFolder()}.
at line 702
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'
at line 716
static string
publicFolder()
Gets the webroot of the project, which may be a subfolder of {see baseFolder()}
at line 737
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.
at line 772
static bool
is_absolute(string $path)
Returns true if a given path is absolute. Works under both *nix and windows systems.
at line 791
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.
at line 810
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.
at line 844
static bool
is_relative_url(string $url)
Checks if a given URL is relative (or root relative) by checking {@link is_absolute_url()}.
at line 861
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.
at line 885
static string
getAbsFile(string $file)
Given a filesystem reference relative to the site root, return the full file-system path.
at line 911
static bool
fileExists($file)
Returns true if the given file exists. Filename should be relative to the site root.
at line 923
static string
absoluteBaseURL()
Returns the Absolute URL of the site root.
at line 938
static string
absoluteBaseURLWithAuth(HTTPRequest $request = null)
Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL.
at line 997
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.
at line 1014
static
forceWWW(HTTPRequest $request = null)
Force a redirect to a domain starting with "www."
at line 1030
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.
at line 1048
static bool
is_cli()
Returns true if this script is being run from the command line rather than the web server.
at line 1059
static string
get_environment_type()
Can also be checked with {@link Director::isDev()}, {@link Director::isTest()}, and {@link Director::isLive()}.
at line 1099
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()}.
at line 1110
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()}.
at line 1121
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()}.
at line 1132
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.