How to load plugins with modules - zend-framework

I have this plugin in the plugins directory within the admin module directory. So, it is in application/modules/admin/plugins/LayoutPlugin.php:
<?php
class LayoutPlugin extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$view->whatever = 'foo';
}
}
I'd like to use it for sending variables to the layout view. It happens that I get Fatal error: Class 'LayoutPlugin' not found every time I try Zend_Controller_Front::getInstance()->registerPlugin(new LayoutPlugin()); in the admin bootstrap.
How do I load a plugin inside a module?

Module bootstraps setup the module autoloader by default, so if you rename your class to Admin_Plugin_LayoutPlugin ZF should be able to find it.
Keep in mind that the admin bootstrap (like all bootstraps) will be run regardless of whether you're in the admin module or not, so if your intention is to assign some extra variables just for your admin pages you'll need to ensure that admin is the current module before registering the plugin.

I know this is an old question but this is always something that bugged me. I don't know if ZF 2 has done anything to solve it (I've not had the chance to play with it yet), but I wrote a plugin loader plugin to deal with this for ZF 1!
The problem is, of course, that even when setting up a module autoloader and keeping your plugins in a module's plugin folder, this only setups up autoloading (which is cross module anyway) not registration. It means you can instantiate the plugin with a line in your application.ini, but it will be autoloaded and registered for every module.
Anyway, here's a possible solution to make sure module plugins are only registered for the active module. Alternatively, instead of providing a class map, you could loop through all the files in a module's plugins directory, but that feels ugly... and probably slow.
<?php
class BaseTen_Controller_Plugin_ModulePluginLoader extends Zend_Controller_Plugin_Abstract {
private $_pluginMap;
public function __construct(array $pluginMap) {
$this->_pluginMap = $pluginMap;
}
public function routeShutdown(Zend_Controller_Request_Abstract $request) {
$module = $request->getModuleName();
if(isset($this->_pluginMap[$module])) {
$front = Zend_Controller_Front::getInstance();
foreach($this->_pluginMap[$module] as $plugin) {
$front->registerPlugin(new $plugin());
}
}
}
}
Because we need to pass a classMap to the constructor, we need to explicity instantiate and register this plugin with the Front Controller rather than with a line in application.ini:
public function _initPluginLoader() {
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new BaseTen_Controller_Plugin_ModulePluginLoader(array(
'default' => array(
'Plugin_Foo',
'Plugin_Bar',
...
),
'foo' => array(
'Foo_Plugin_Foo',
'Foo_Plugin_Bar',
...
)
)));
}
The earliest the plugin can run is at routeShutdown otherwise we won't know the active module. What this means though is that any other plugins registered using this method can only run from dispatchLoopStartup onwards. Mostly, we're probably interested in preDispatch and postDispatch hooks but worth bearing in mind.

Related

ZF not autoloading models and forms from module

I have come across a strange problem with Zend_Framework, I can not load forms or models from any module other than default.
I have the following line of code in my controller (in the user module)
$myAccountModel = new User_Model_MyAccount();
However all i get is the error
Fatal error: Class 'User_Model_MyAccount' not found in F:\My Webs\freedate\application\modules\user\controllers\MyAccountController.php on line 13
I have checked the files path and class name and all is correct, I have this project setup similar to other ZF projects I have done in the past, the only difference is that this is on a WAMP server rather than a LAMP server.
If I try to load a model or form from the default module it loads fine, these line of code produce no errors and the classes load fine.
$loginForm = new Form_Login();
$loginModel = new Model_Login();
If someone can shed some light as to what is going on here it would be most helpful as I have now hit a brick wall!!
I am using ZF 1.11.11 btw.
Many thanks
Garry
[EDIT]
This is definatly a probelm with ZF autoloader, if I add the following line the error goes away.
require_once(APPLICATION_PATH . '/modules/user/models/MyAccount.php');
In my application.ini i have
; modules
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules[] =
and in my bootstrap.php I have
/** * Initialize autoloader
* #return Zend_Loader_Autoloader
*/
protected function _initAutoload() {
return Zend_Loader_Autoloader::getInstance();
}
/** * Initialize module autoloader
* #return Zend_Application_Module_Autoloader
*/
protected function _initModuleAutoload() {
$modelLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH . '/modules/default'));
return $modelLoader;
}
Have you tried to add an empty Module_Bootstrap to the specific module? Like so:
<?php
class User_Bootstrap extends Zend_Application_Module_Bootstrap
{// nothing in here except you really want to do anything here ;)}
Once you do this, you can remove the _initAutoload() and _initModuleAutoload() methods from your bootstrap. When you create a module bootstrap, the Zend_Application_Module_Autoloader is automatically created by default for that module.
See The Module Resource Autoloader

PHPExcel class not found in Zend Autoloader

I am struggling with namespaces in Zend Framework (at least I think it's a namespace issue).
I want to integrate PHPExcel into my Zend project. Relevant file structure is as follows:
/
-library
-ABCD
-PHPExcel
-Zend
-ZendX
-PHPExcel.php
Custom classes work fine, after
Zend_Loader_Autoloader::getInstance()->registerNamespace('ABCD_');
in the bootstrap. Also, those classes are all named ABCD_blahdeblah.
However, doing registerNamespace('PHPExcel_') doesn't help Zend find the appropriate classes. When I try
$sheet = new PHPExcel;
in the controller, I get a "Class not found" error. I am guessing that this is either because classes in PHPExcel aren't named with the namespace prefix, or because the main PHPExcel.php file sits outside of the namespace I've just declared. But the PHPExcel structure demands that it sit in the parent directory of the rest of the class/font/etc files.
Any pointers would be greatly appreciated.
Thanks in advance.
Create an autoloader for PHPExcel and add it to the Zend autoloader stack.
In library/My/Loader/Autoloader/PHPExcel.php:
class My_Loader_Autoloader_PHPExcel implements Zend_Loader_Autoloader_Interface
{
public function autoload($class)
{
if ('PHPExcel' != $class){
return false;
}
require_once 'PHPExcel.php';
return $class;
}
}
And in application/configs/application.ini:
autoloadernamespaces[] = "My_"
Then, in application/Bootstrap.php:
protected function _initAutoloading()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(new My_Loader_Autoloader_PHPExcel());
}
Then you should be able to instantiate PHPExcel - say, in a controller - with a simple:
$excel = new PHPExcel();
The only sticky part is all of this is how PHPExcel handles loading all its dependencies within its own folder. If that is done intelligently - either with calls like require_once basename(__FILE__) . '/someFile.php' or with its own autoloader that somehow doesn't get in the way of the Zend autoloader - then all should be cool. #famouslastwords
Nowadays composer is a frequently used tool that wasn't so popular back in 2012. Even older projects built in ZF1 can make use of composer and its autoloader.
How to get all your libraries to work without having to add custom autoloaders to your application.ini each time?
Make use of composer's autoloader
First, start with setting up composer.json. Once created, run composer install to gather all required packages and create composer's autoloader.
Now, let's update your project's public/index.php. From now on all requirements that are loaded via composer will be autoloaded.
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));
// Include composer autoloader
require_once __DIR__ . '/../vendor/autoload.php';
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
array( 'config' => APPLICATION_PATH . '/configs/application.ini' )
);
$application->bootstrap();
$application->run();
Try modifying the PHPExcel autoloader:
Add
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
as the first two lines of the Register() method in /Classes/PHPExcel/Autoloader.php, immediately before
return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
I've had a similar problem with both an exel-librare (phpxls) and a pdf-library (fpdf) and after some different tries I just settled with including the required file from the library manually and go from there. Booth phpxls and fdpd can then handle everything else without interfering with the zend autoloader methods.
A psudo_code example would look like this, where I return a object of the desired class and then can continue to work with that. You could offcourse choose to include things in the constructor and build from that.
<?php
class exelClass{
public function exelFunction(){
require_once 'required_file.php';
$exelObject = new exelObject();
return $exelObject->Output();
}
}
?>
This solution might not be that elegant, but I found that it was the easiest way to enable different types of libraries to co-exist without differnet autoloaders or magic functions interfearing with each other.

preDispatch() is not called in Controller Plugin

class My_Plugin extends Zend_Controller_Plugin_Abstract
{
public function init()
{
print 'this is working just fine';
}
public function preDispatch( Zend_Controller_Request_Abstract $request )
{
Zend_Debug::dump($request);
print 'why is it not working';
exit;
die(':('); // not dieing either
}
}
The plugin is registered in /configs/application.ini file. ZF does see it, because init() function works perfectly fine. But nothing I put into preDispatch seems to work.
P.S. the only purpose of this plugin is to determine what language is used from the parameter in URL, and set Zend_Locale to it. So that I won't need to do it in any controller or view ever again, instead relying on Zend_Locale, Zend_Translate, etc. But I can't do that in plugin's init() and preDispatch() doesnt work at all :/ The lack of proper documentation for ZF starting to drive me crazy
The problem was I needed to add one line to application.ini:
resources.frontController.plugins.myplugin = Plugins_My_Plugin
Everything works now.

Zend_Layout for modules

How can I make every module have it's own layouts directory?
I.e. when I don't have any modules my layout entry in config file looks like this:
resources.layout.layoutPath = APPLICATION_PATH "/layouts"
I try entering i.e.
; Layout directory for admin module
admin.resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts"
Where admin is module name; but it doesn't work. For some strange reason ZF looks for module layouts in /module/admin/views/scripts directory.
I also have a separate module.ini config file for every module as per this tutorial, alas layout path there gets ignored as well. Also I've been trying to follow this modules layout tutorial but it didn't work, I guess due to differences in ZF versions (tutorial is rather old). So I don't know what else to do
Using plugin from the tutorial you are talked about:
class My_Controller_Plugin_RequestedModuleLayoutLoader extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
$moduleName = $request->getModuleName();
if (isset($config[$moduleName]['resources']['layout'])) {
Zend_Layout::startMvc($config[$moduleName]['resources']['layout']);
}
}
}
application.ini
resources.frontController.plugins.layoutloader = My_Controller_Plugin_RequestedModuleLayoutLoader
module.ini:
resources.layout.layout = "Admin"
resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts/scripts"
Working fine.
A slightly alternate method to Ololo recommendation (which is a great way to do it)..
class YourApp_Controller_Plugin_Modulelayout extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
if ($module != 'default')
{
if (file_exists(APPLICATION_PATH . '/layouts/' . $module . '.html')) {
Zend_Layout::getMvcInstance()->setLayout($module);
}
}
}
}
Place this controller plugin in /library/YourApp/Controller/Plugin/Modulelayout.php
Then save your module layouts as the module name in your layouts folder (E.g., /layout/admin.phtml). If it does not find a layout for that module, it will default back to layout.phtml or whatever you originally set it to.
Have a look at this gist - https://gist.github.com/891384
This uses a combination of
Action helper to inspect the requested module and given a matching configuration, change the layout's layout and layoutPath properties in the preDispatch hook
Application resource plugin to capture module layout options, inject them into the above helper and add it to the helper broker
Happened to me too I got around it by using this line in my controller (I created a init function)
Zend_Layout::startMvc(array('layoutPath' => APPLICATION_PATH . '/modules/admin/layouts'));
As of Zend Framework 1.12 (Haven't tested it on previous releases):
Create your modules
Initialize the layout in your prefered fashion. For example in application.ini as zend tools does it:
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
Create a layout inside each module with the default layout name inside the modules path to "views/scripts/" for example "application/modules/default/views/scripts/layout.phtml"
Don't forget to create one for the default module as it will be your fallback layout!
DO NOT create the default layout inside /application/layouts/scripts or this won't work
You are ready to run!
When Zend_Layout doesn't find the default layut it will look into the modules folders for it.
If you need some extra tweaking you may create a plugin and assign it to the layout object itself. For example, inside application.ini:
resources.layout.pluginClass = "MyLibrary_Controller_Plugin_Layout"
...or in the Bootstrap:
Zend_Layout::getMvcInstance()->setPluginClass("MyLibrary_Controller_Plugin_Layout");
Cheers!

Zend Action helper

I am learning how to use Zend framework and realise that the action helper is something that would be useful.
I have set up a default installation of Zend on my machine, but I dont know where the helper file needs to go, what I need to put in the bootstrap file and how I use it. Can anyone point me in the right direction please - the ZF user guide is not to clear to me.
Thanks
John
Two thoughts for where to place your custom action-helpers:
In a separate, custom library
In the folder application/controllers/helpers
These ideas are not exclusive. Functionality that is general enough to work in multiple projects should probably be pulled into a separate library. But for functionality that is application-specific, there is an argument that it could be somewhere in the application folder.
#Jurian has already described the "separate-library" approach. For app-specific helpers, you can do as follows:
For a helper called myHelper, create a class Application_Controller_Helper_MyHelper in the file application/controllers/helpers/MyHelper.php. In Bootstrap, you have something like:
protected function _initAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'Application',
'basePath' => APPLICATION_PATH,
));
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH . '/controllers/helpers',
'Application_Controller_Helper_');
return $autoloader;
}
Then your helper can be invoked in a controller by using:
$this->_helper->myHelper;
As you can see, this presumes you are using appNamespace 'Application'. If not, you can (must!) modify your class names to accommodate your circumstance.
Cheers!
You can place action helpers in your own library. Besides library/Zend where all the Zend stuff is around, you can create a library/MyLibrary folder (MyLibrary is arbitrary chosen) and put the action helpers there.
A good place is the library/MyLibrary/Controller/Action/Helper folder you need to create and place your action helper there (i.e. Navigation.php). In this file, create the class MyLibrary_Controller_Action_Helper_Navigation.
The next step is to add the action helper to the HelperBroker of the Zend Framework during bootstrap. Therefore, create a new method in your Bootstrap.php file and add this function:
protected function _initActionHelpers ()
{
Zend_Controller_Action_HelperBroker::addHelper(
new MyLibrary_Controller_Action_Helper_Navigation()
);
}
One last remark is you need to configure the use of this library by adding this rule to your application.ini:
autoLoaderNameSpaces[] = "MyLibrary_"
You can do this through your application.ini file like so
resources.view[] =
resources.view.helperPath.Default_View_Helper_ = APPLICATION_PATH "/views/helpers/"
Then in your views/helpers path you can create a file like Time.php. This file would contain the following code:
<?php
class Default_View_Helper_Time extends Zend_View_Helper_Abstract
{
public function time()
{
$date = new Zend_Date();
return $date->get(Zend_Date::TIME_MEDIUM);
}
}
?>
To use this in your view scripts you would use
<?=$this->time()?>
Which would display the current time using your new View_Helper
You can avoid having to register your action helper namespace and path within the Bootstrap.php by declaring them in the application.ini instead like so:
resources.frontController.actionHelperPaths.My_Controller_Action_Helper = APPLICATION_PATH "/controllers/helpers"
Simply replace My_Controller_Action_Helper with your desired namespace, and modify the helpers directory path accordingly.
The helper can be initialized the same way:
$this->_helper->myHelper;
As mentioned by the docs, registering the prefix or path of the helpers is usually preferred because helpers would not be initialized until they are called like in the snippet above.
Of course, instantiating and passing helpers to the broker is a bit
time and resource intensive, so two methods exists to automate things
slightly: addPrefix() and addPath().
http://framework.zend.com/manual/1.12/en/zend.loader.pluginloader.html
Adding the config entry to the application.ini follows the same suggested pattern.