Működési elv
Egy MVC alkalmazás beállítása és felkészítése az indulásra egyre növekvő
mennyiségű kódot igényelt, ahogy egyre több és több lehetőség állt rendelkezésre: beállítani
az adatbázist, a nézetet és a nézet segédeket, az elrendezéseket, bejegyezni a
bővítményeket, művelet segédeket és a többi.
Ezen felül gyakoran igény lehet ugyanazon kód használata a tesztek, ütemezett feladatok vagy
egy webszolgáltatás rendszertöltéséhez. Miközben lehetséges egyszerűen beilleszteni a
rendszertöltő állományt, gyakori, hogy bizonyos beállítások környezetre jellemzők – nem
szükséges az MVC egy ütemezett feladathoz, vagy az adatbázis réteg egy
szolgáltatáshoz.
A Zend_Application célja ennek leegyszerűsítése és az újrahasznosítás
elősegítése a rendszertöltés OOP mintákba zárásával.
A Zend_Application három részre bontható:
Zend_Application: betölti a PHP
környezetet, beleértve az include_path-t és az automatikus betöltést, illetve
példányosítja a kért rendszertöltő osztályt.
Zend_Application_Bootstrap: felületeket nyújt a rendszertöltő
osztályoknak. A Zend_Application_Bootstrap_Bootstrap a
legtöbb rendszertöltővel szemben támasztható igényt kielégítő funkcionalitást nyújt,
beleértve a függőség-ellenőrző algoritmusokat és a rendszertöltő erőforrások igény
szerinti betöltését.
A Zend_Application_Resource szabványos, egy rendszertöltő
példány által igény szerint betölthető erőforrásokhoz nyújt felületet, csakúgy, mint
több kész megvalósítást.
A fejlesztők a Zend_Application_Bootstrap_Bootstrap kiterjesztésével
vagy (legkevesebb) a Zend_Application_Bootstrap_Bootstrapper
megvalósításával hozhatnak létre rendszertöltőt alkalmazásukhoz. A belépési pont
(public/index.php, pl.) betölti és példányosítja a
Zend_Application-t
a pillanatnyi környezet és
a rendszertöltés beállításainak
átadásával.
Utóbbiak magukban foglalják a rendszertöltő osztályt tartalmazó állomány elérési útját,
illetve igény szerint:
további include_path összetevőket;
további automatikus betöltéshez bejegyzendő névtereket;
beállítandó php.ini értékeket;
a rendszertöltő osztály nevét (ha nem „Bootstrap”)
erőforrás előtagat a az elérési utakhoz;
használandó erőforrásokat (az osztály neve vagy rövid név szerint);
további elérési utakat konfigurációs állományok betöltéséhez, illetve
további konfigurációs beállításokat.
A beállítások érkezhetnek egy tömbben, egy Zend_Config objektumban
vagy egy konfigurációs állomány elérési útja képében.
Rendszertöltés
A Zend_Application felelősségi körébe tartozik az alkalmazás
rendszertöltőjének végrehajtása is. Egy rendszertöltőnek legkevesebb meg kell
valósítania Zend_Application_Bootstrap_Bootstrapper-t, mely
a következő API-t határozza meg:
Ez az API lehetővé teszi a rendszertöltőnek a környezet és
beállítások fogadását az alkalmazás objektumtól, hogy jelentsen az erőforrásokról,
melyek indításáért felelős, majd betöltse és futtassa az alkalmazást.
A felület megvalósítható önállóan, lehetőség van a
Zend_Application_Bootstrap_BootstrapAbstract kiterjesztésére
vagy a Zend_Application_Bootstrap_Bootstrap használatára.
Ezek mellett egy sor más dolog is van, mellyel érdemes megismerkedni.
Erőforrás tagfüggvények
A Zend_Application_Bootstrap_BootstrapAbstract megvalósítás
egy egyszerű egyezményt nyújt erőforrás tagfüggvények meghatározására. Minden védett
tagfüggvény, mely az _init előtaggal kezdődik, erőforrás
tagfüggvénynek számít.
Egy adott erőforrás tagfüggvény betöltéséhez a bootstrap()
metódus használatos az erőforrás nevének megadásával. A név a tagfüggvény neve az
_init előtag elhagyásával.
Több tagfüggvény betöltéséhez egy tömböt kell átadni, az összeséhez pedig semmit.
Vegyük a következő rendszertöltő osztályt:
Az _initFoo() tagfüggvény betöltéséhez a következő a
teendő:
bootstrap('foo');
]]>
Az _initFoo() és az _initBar()
betöltéséhez a következő:
bootstrap(array('foo', 'bar'));
]]>
Az öszes betöltéséhez a bootstrap() argumentumok nélkül
hívandó:
bootstrap();
]]>Bootstraps that use resource plugins
To make your bootstraps more re-usable, we have provided the
ability to push your resources into resource plugin classes.
This allows you to mix and match resources simply via
configuration. We will cover how
to create resources later; in
this section we will show you how to utilize them only.
If your bootstrap should be capable of using resource plugins,
you will need to implement an additional interface,
Zend_Application_Bootstrap_ResourceBootstrapper.
This interface defines an API for locating, registering, and
loading resource plugins:
Resource plugins basically provide the ability to create
resource intializers that can be re-used between applications.
This allows you to keep your actual bootstrap relatively clean,
and to introduce new resources without needing to touch your
bootstrap itself.
Zend_Application_Bootstrap_BootstrapAbstract (and
Zend_Application_Bootstrap_Bootstrap by extension)
implement this interface as well, allowing you to utilize
resource plugins.
To utilize resource plugins, you must specify them in the
options passed to the application object and/or bootstrap. These
options may come from a configuration file, or be passed in
manually. Options will be of key to options pairs, with the key
representing the resource name. The resource name will be the
segment following the class prefix. For example, the resources
shipped with Zend Framework have the class prefix
"Zend_Application_Resource_"; anything following this would
be the name of the resource. As an example,
array(
'FrontController' => array(
'controllerDirectory' => APPLICATION_PATH . '/controllers',
),
),
));
]]>
This indicates that the "FrontController" resource should be
used, with the options specified.
If you begin writing your own resource plugins, or utilize
third-party resource plugins, you will need to tell your
bootstrap where to look for them. Internally, the bootstrap
utilizes Zend_Loader_PluginLoader, so you will only
need to indicate the common class prefix an path pairs.
As an example, let's assume you have custom resource plugins in
APPLICATION_PATH/resources/ and that they share the
common class prefix of My_Resource. You would then
pass that information to the application object as follows:
array(
'My_Resource' => APPLICATION_PATH . '/resources/',
),
'resources' => array(
'FrontController' => array(
'controllerDirectory' => APPLICATION_PATH . '/controllers',
),
),
));
]]>
You would now be able to use resources from that directory.
Just like resource methods, you use the bootstrap()
method to execute resource plugins. Just like with resource
methods, you can specify either a single resource plugin,
multiple plugins (via an array), or all plugins. Additionally,
you can mix and match to execute resource methods as well.
bootstrap('FrontController');
// Execute several:
$bootstrap->bootstrap(array('FrontController', 'Foo'));
// Execute all resource methods and plugins:
$bootstrap->bootstrap();
]]>Resource Registry
Many, if not all, of your resource methods or plugins will
initialize objects, and in many cases, these objects will be
needed elsewhere in your application. How can you access them?
Zend_Application_Bootstrap_BootstrapAbstract
provides a local registry for these objects. To store your
objects in them, you simply return them from your resources.
For maximum flexibility, this registry is referred to as a
"container" internally; its only requirements are that it is an
object. Resources are then registered as properties named after
the resource name. By default, an instance of
Zend_Registry is used, but you may also specify any
other object you wish. The methods setContainer()
and getContainer() may be used to manipulate the
container itself. getResource($resource) can be
used to fetch a given resource from the container, and
hasResource($resource) to check if the resource has
actually been registered.
As an example, consider a basic view resource:
You can then check for it and/or fetch it as follows:
hasResource('view')) {
$view = $bootstrap->getResource('view');
}
// Via the container:
$container = $bootstrap->getContainer();
if (isset($container->view)) {
$view = $container->view;
}
]]>
Please note that the registry and also the container is not global. This
means that you need access to the bootstrap in order to fetch
resources. Zend_Application_Bootstrap_Bootstrap
provides some convenience for this: during its
run() execution, it registers itself as the front
controller parameter "bootstrap", which allows you to fetch it
from the router, dispatcher, plugins, and action controllers.
As an example, if you wanted access to the view resource from
above within your action controller, you could do the following:
getInvokeArg('bootstrap');
$view = $bootstrap->getResource('view');
// ...
}
}
]]>Dependency Tracking
In addition to executing resource methods and plugins, it's
necessary to ensure that these are executed once and once
only; these are meant to bootstrap an application, and
executing multiple times can lead to resource overhead.
At the same time, some resources may depend on other
resources being executed. To solve these two issues,
Zend_Application_Bootstrap_BootstrapAbstract
provides a simple, effective mechanism for dependency
tracking.
As noted previously, all resources -- whether methods or plugins
-- are bootstrapped by calling bootstrap($resource),
where $resource is the name of a resource, an array
of resources, or, left empty, indicates all resources should be
run.
If a resource depends on another resource, it should call
bootstrap() within its code to ensure that resource
has been executed. Subsequent calls to it will then be ignored.
In a resource method, such a call would look like this:
bootstrap('FrontController');
// Retrieve the front controller from the bootstrap registry
$front = $this->getResource('FrontController');
$request = new Zend_Controller_Request_Http();
$request->setBaseUrl('/foo');
$front->setRequest($request);
// Ensure the request is stored in the bootstrap registry
return $request;
}
}
]]>Resource Plugins
As noted
previously, a good way to create re-usable bootstrap resources and to
offload much of your coding to discrete classes is to utilize resource
plugins. While Zend Framework ships with a number of standard
resource plugins, the intention is that developers should write
their own to encapsulate their own initialization needs.
Resources need only implement
Zend_Application_Resource_Resource, or, more simply
still, extend
Zend_Application_Resource_ResourceAbstract. The basic
interface is simply this:
The interface defines simply that a resource should accept options
to the constructor, have mechanisms for setting and retrieving
options, have mechanisms for setting and retrieving the bootstrap
object, and an initialization method.
As an example, let's assume you have a common view intialization you
use in your applications. You have a common doctype, CSS and
JavaScript, and you want to be able to pass in a base document title
via configuration. Such a resource might look like this:
getView();
}
public function getView()
{
if (null === $this->_view) {
$options = $this->getOptions();
$title = '';
if (array_key_exists('title', $options)) {
$title = $options['title'];
unset($options['title']);
}
$view = new Zend_View($options);
$view->doctype('XHTML1_STRICT');
$view->headTitle($title);
$view->headLink()->appendStylesheet('/css/site.css');
$view->headScript()->appendfile('/js/analytics.js');
$viewRenderer =
Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
$this->_view = $view;
}
return $this->_view;
}
}
]]>
As long as you register the prefix path for this resource plugin,
you can then use it in your application. Even better, because it
uses the plugin loader, you are effectively overriding the shipped
"View" resource plugin, ensuring that your own is used instead.