First let me start by saying I am fairly new to ZF and with this post I am
primarily looking for feedback for improvement from the Zend experts on my
solution and hopefully, if list solution is reasonable, others may have some
information, where I found it difficult to find.
My Goal: With my ZF Application setup for modules
(module/controller/action), I wanted to:
1. remove index from the URL (I find it a nuisance)
2. if I requested /module/action, that the App would catch the error of
action not being a controller and check to see if it was an action in the
index controller of that module. So I could use /event/list instead of
/event/index/list.
Here is my solution:
class App_Controller_Plugin_CustomRoutes extends
Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request )
{
$dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
$moduleName = $request->getModuleName(); //e.g.
user
$controllerName = $request->getControllerName(); //e.g. index
$actionName = $request->getActionName(); //e.g.
list
// example: creates Module_IndexController class name
// out of $moduleName and $controllerName
$className = $dispatcher->formatControllerName($moduleName . '_' .
$controllerName); //e.g. Module_IndexController
$controllerFileName =
$dispatcher->formatControllerName($controllerName) . '.php'; //e.g.
IndexController.php
// check if a class name was created
if ($controllerFileName)
{
$validControllerFile =
Zend_Loader::isReadable($controllerFileName);
if ($validControllerFile)
{
// this is a valid controller - exit now
return;
}
else
{
// Couldn't load the class (controller).
// lets see if this is an action in the index controller
$actionName = $controllerName;
$controllerName =
$dispatcher->getDefaultControllerName();
// example: takes Index and creates IndexController
class name to
see if it exists
$className =
$dispatcher->formatControllerName($moduleName . '_' .
$controllerName);
$controllerFileName =
$dispatcher->formatControllerName($controllerName)
. '.php';
if($className && $controllerFileName)
{
try
{
$methodName =
$dispatcher->formatActionName($actionName);
Zend_Loader::loadFile($controllerFileName,null,true);
$class = new ReflectionClass( $className );
if( $class->hasMethod( $methodName ) )
{
// we only arrive here if can't find
controller or action
$request->setControllerName($controllerName);
$request->setActionName($actionName);
// this will force plugins to
fire again
$request->setDispatched( false
);
}
else
{
// action does not exist either, return so
404 will be
thrown
return;
}
}
catch (Zend_Exception $e)
{
// Couldn't load the class with method.
No need to act,
// just catch the exception and fall out of the
// if
}
}
}
}
}
}
Thank You,
David
--
View this message in context:
http://www.nabble.com/Looking-for-code-feedback-tp23377593p23377593.html
Sent from the Zend Framework mailing list archive at Nabble.com.