Programmer's Reference Guide

Plugins

Utilisation de conventions de dossiers modulaires

Introduction

Les conventions de dossiers vous permettent de séparer les différentes applications MVC dans des unités isolées et les réutiliser dans le contrôleur frontal. Voici une illustration :

  1. docroot/
  2.     index.php
  3. application/
  4.     default/
  5.         controllers/
  6.             IndexController.php
  7.             FooController.php
  8.         models/
  9.         views/
  10.             scripts/
  11.                 index/
  12.                 foo/
  13.             helpers/
  14.             filters/
  15.     blog/
  16.         controllers/
  17.             IndexController.php
  18.         models/
  19.         views/
  20.             scripts/
  21.                 index/
  22.             helpers/
  23.             filters/
  24.     news/
  25.         controllers/
  26.             IndexController.php
  27.             ListController.php
  28.         models/
  29.         views/
  30.             scripts/
  31.                 index/
  32.                 list/
  33.             helpers/
  34.             filters/

Ci dessus, le nom du module est utilisé comme préfixe pour les contrôleurs qu'il possède. Il y a donc trois contrôleurs : "Blog_IndexController", "News_IndexController", et "News_ListController". Deux contrôleurs dans le module par défaut sont aussi définis, "IndexController" et "FooController". Ceux-ci ne possèdent pas le nom du module dans leur nom. Cet exemple d'arborescence conseillée sera utilisé dans ce chapitre.

Note: Pas de namespace pour le module par défaut
Notez que dans le module par défaut, les contrôleurs n'ont pas besoin d'être préfixés par le nom du module ("Default_"). Ils sont simplement distribués tels quels. Ce n'est pas le cas pour les autres contrôleurs.

Alors, comment utiliser une structure telle que celle-ci ?

Spécification des dossiers de modules

La première chose à faire est d'indiquer au contrôleur frontal où se trouvent les dossiers contenant les contrôleurs d'action. Passez un array ou une string à setControllerDirectory(), ou alors une string à addControllerDirectory(). Si vous utilisez les modules, ces appels de méthodes changent quelque peu.

Pour setControllerDirectory(), un tableau est requis. Les paires clé/valeur représentent le nom du module, et le chemin des contrôleurs. La clé default est utilisée pour indiquer les contrôleurs globaux (dont le nom ne comporte pas le module). Chaque option doit comporter une indication vers un chemin, et la clé default doit être présente :

  1. $front->setControllerDirectory(array(
  2.       'default' => '/path/to/application/controllers',
  3.       'blog'    => '/path/to/application/blog/controllers'
  4. ));

addControllerDirectory() prend en paramètre une string décrivant un chemin vers des contrôleurs. Si vous voulez indiquer un module, passez le en second paramètre. Sinon, le chemin sera ajouté au module default.

  1. $front->addControllerDirectory('/path/to/application/news/controllers',
  2.                                'news');

Enfin, si vous avez un dossier spécial regroupant tous vos modules, indiquez le grâce à addModuleDirectory() :

  1. /**
  2. * Sur cet exemple :
  3. * application/
  4. *     modules/
  5. *         default/
  6. *             controllers/
  7. *         foo/
  8. *             controllers/
  9. *         bar/
  10. *             controllers/
  11. */
  12. $front->addModuleDirectory('/path/to/application/modules');

Dans le code ci dessus, vous déclarez 3 modules en une méthodes. Celle-ci s'attend à la structure comprenant les modules default, foo, et bar, chacun devant posséder un dossier controllers

Si le dossier "controllers" ne vous convient pas, changez son nom à l'aide de setModuleControllerDirectoryName() :

  1. /**
  2. * Le dossier des contrôleurs s'appelle désormais 'con'
  3. * application/
  4. *     modules/
  5. *         default/
  6. *             con/
  7. *         foo/
  8. *             con/
  9. *         bar/
  10. *             con/
  11. */
  12. $front->setModuleControllerDirectoryName('con');
  13. $front->addModuleDirectory('/path/to/application/modules');

Note: Si vos dossiers de modules ne doivent pas utiliser de sous dossier pour les contrôleurs, alors passez une valeur vide à setModuleControllerDirectoryName().

Routage des modules

La route par défaut, Zend_Controller_Router_Rewrite est un objet de type Zend_Controller_Router_Route_Module. Cette route traite les schémas de routage suivants :

  • :module/:controller/:action/*

  • :controller/:action/*

Ainsi, elle va trouver les contrôleurs et actions, avec ou sans module les précédant. Un module ne sera trouvé que si sa clé existe dans le tableau d'options passé au contrôleur frontal ou au distributeur.

Module ou contrôleur Default global

Dans le routeur par défaut, si aucun contrôleur n'est indiqué dans l'URL, un contrôleur par défaut sera utilisé (IndexController, sauf si l'on décide de changer ce paramètre). Avec des modules indiqués dans l'URL, si aucun contrôleur n'est indiqué, alors le distributeur cherchera dans le module demandé le contrôleur par défaut. Si celui-ci est absent, c'est celui du module "default" qui sera utilisé.

Si vous voulez renvoyer directement vers le contrôleur par défaut du module "default", passez le paramètre useDefaultControllerAlways à TRUE dans le contrôleur frontal :

  1. $front->setParam('useDefaultControllerAlways', true);

Plugins

Comments

The directory examples here don't seem to match the recommended layout here
where the default module is a level higher than the modules directory.
Is there a way i can use different layouts for different modules
@Posted by: Imran Zulfiqar on: 2010-04-22 10:27:31

yes
Yeah, great, *claps*. WHERE EXACTLY is this supposed to be configured?

This is the same problem throughout the ZF documentation! Stop crapping on about how awesome the framework is and put the examples in CONTEXT!
@ Imran Zulfiqar & Jebas

The layout shipped with ZF is implemented as a front controller plugin.
You can easily extend that one and work some magic to switch the layout according to the requested module. And configure the layout resource to use your own class.

My take (on pastebin) :
http://pastebin.org/358208

And in application.ini :

resources.layout.layout = layout
resources.layout.layoutPath = APPLICATION_PATH "/views/layouts"
resources.layout.pluginClass = "My_Controller_Plugin_ModuleLayout"
Please don't use 'con' as example directory name to show how "setModuleControllerDirectoryName" works. 'con' is a forbidden foldername on windows bases machines.

See: http://www.theinquirer.net/inquirer/news/1023739/windows
I have to agree with Jebas, where exactly are you supposed to configure this? I've set up the application/modules directory structure and am accessing controllers just fine with e.g., /MyWebsite/module/controller/action, however, I still must include or require resources such as Storefront_Model_CartModel.
I've tried to configure in my bootstrap,

public function run()
{
parent::run();
$front = $this->getResource('FrontController');
$front->addModuleDirectory('application/modules');
}

and this appears to work (no exceptions thrown) but to no avail, I still need to include or require.
You forgot to say in which file we should add those lines.
In which file?
Obviously nobody at Zend has the time to teel anyone where these changes should be placed.
The following should be added to your Bootstrap.php file.

protected function _initFrontModules() {
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->addModuleDirectory(APPLICATION_PATH . '/modules');
}
Obviously nobody at Zend has the time to teel anyone where these changes should be placed.
The following should be added to your Bootstrap.php file.

protected function _initFrontModules() {
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->addModuleDirectory(APPLICATION_PATH . '/modules');
}
How the zf confuse guys?
Why not explore some example rather than commend.
In ZF 1.1* you can create a modular application without touching the code just edit appliocation.ini
Example gere : http://updel.com/zend-framework-modular-application/
Wow - thanks KEVIN... appreciated.

I was starting to again feel like, if I don't just know, then why am at Zend.com trying to find the answer. I mean, c'mon, with the above being so clear now. pff
And how can i load a model class which is located in "modules/news/models/news.php"?
I'm using this modular structure:
application
default
controllers
models
views
admin
controllers
models
views

and i want to keep all my models in default/models and all modules can use. How can i do this???

When i made the class 'Apllication_Model_Test' the class was not found. What and WHERE i have to set up for i use my models on all modules?

Thanks for any help!!!
Renan30
Big thanks to Kevin. I have found this a few times to day at Zend - great docs, but the vital part of where to put the code is missing.
Easiest way to do module configuration is to do add the following code in configs/application.ini

resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules=true

and removing the line
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

In ZF 1.11,

I used zend tool:

zf create module default

Which adds a directories into : APPLICATION_PATH /modules/default
and appends to the application.ini config file:


resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.params.prefixDefaultModule = "1"


I then moved my IndexController, ErrorController and view scripts into the default module's appropriate directories but got this error:

Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller class ("Default_ErrorController")'

Removing this line from application.ini solves this problem:
resources.frontController.params.prefixDefaultModule = "1"
In response to Tiffany, I also found that keeping the resources.frontController.params.... line but changing it to blank works:

resources.frontController.params.prefixDefaultModule = ""
I do not understand why no mention of that file or directory is that this code Pharmacopoeia for example:

$ front-> setControllerDirectory (array (
'default' => '/ path / to / application / controllers',
'blog' => '/ path / to / application / blog / controllers'
));

All examples, tutorials or the vast majority do not understand what part they copied the codes mentioned, that I tell people that just start with zend.
this is the fastest, easiest and accurate way of creating module that i found after 2 days of my struggle and searching: http://www.christiansouth.com/php/using-zf-tool-to-create-a-modular-application/
Hi Tiffany, I have the same problem when use "prefixDefaultModule=true" with "Default_ErrorController".

I solved the problem by using this:
resources.frontController.prefixDefaultModule = "Default"

Don't remove "Default" from ErrorController because it seems not to be natural. What if you don't want the default module named "default"? :)
I know that this stuff is great and free, but come on guys, is it to hard to just explain how to use specific layouts for each module? Jesus...
@Ilich

And how can i load a model class which is located in "modules/news/models/news.php"?

It depends exactly on how you have named things. Here is how I solved the same problem.

My file structure is:
application > modules > module which contains a folder for controllers, models, views and a Bootstrap.php file.

My module Bootstrap.php file is:

class modulename_Bootstrap extends Zend_Application_Module_Bootstrap
{

}


I created a basic model which looks something like this:

class Module_Model_Bio
{
    
    public function fetchAll() 
    {
    // fetch all records from the table
    $rowset = $this->_dbTable->fetchAll();
         
    return $rowset->toArray();
     
    } //end fetchAll
    
}


Then in my controller, I can instantiate this model with the following (note the lowercase module after the keyword new):

class Module_BioController extends Zend_Controller_Action
{

    public function indexAction()
    {
        [b]$bio = new module_Model_Bio();[/b]
        $this->view->entries = $bio->fetchAll();
    }
}


I could be wrong, but I believe it is lowercase because that is how my module was named and how it is written in my module's Bootstrap.php file. If I instantiate it in a different case (camel case) it will not be found.
@Ilich

Please note the rule following line:

[b]$bio = new module_Model_Bio();[/b]


should just be:

$bio = new module_Model_Bio();
I wrote a short document for myself that describe how to implement this, I also attached a skeleton for a modules based application:
http://www.ranweb.net/wpEn/?p=406
Maybe it will help somebody...

+ Add A Comment

Please do not report issues via comments; use the ZF Issue Tracker.

If you have a JIRA/Crowd account, we suggest you login first before commenting.

  • BBCode is allowed in the comment markup

  • Select a Version

    Languages Available

    Components

    Search the Manual