Remove Index from indexController in zend framework application - php

I want to remove index word from url from every action generated from index controller.
domain.com/index/user/id/1
It should be domain.com/user/id/1
and
domain.com/index/home
It should be domain.com/home
How can I do this? Please let me know if you have solution.
I am using zf1.12

You can do it in your Bootstrap.php (altough in application.ini). Add this to Bootstrap:
Bootstrap.php (untested)
/**
* Setup Routig.
* Now all calls are send to indexController like
* URL/ACTION-1
* URL/ACTION-2
*
* #return void
**/
protected function _initRouters()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = new Zend_Controller_Router_Route(
':action/*',
array(
'controller' => 'index',
'action' => 'index'
)
);
$router->addRoute('default', $route);
}
Application.ini (untested)
routes.index.type = "Zend_Controller_Router_Route"
routes.index.route = "/"
routes.index.defaults.module = "default"
routes.index.defaults.controller = "index"
routes.index.defaults.action = "index"

Related

How to set routing in Zend Framework 1.12

My aim is to have product links like:
domain.com/test-product
domain.com/second-test-product
instead of:
domain.com/products/product/id/5
domain.com/products/product/id/123
Info about each product is get in ProductsController in productAction().
It works fine:
ProductsController:
public function productAction() {
$products = new Application_Model_DbTable_Products();
$nicelink = $this->_getParam('nicelink', 0);
$this->view->product = $products->fetchRow($products->select()->where('product_nicelink = ?', $nicelink));
// nicelink is always unique
}
The link to this method looks like:
for ($i=0; $i < count($this->products); $i++) {
echo 'LINK';
}
Info about each product is displayed in product.phtml view:
<?php echo $this->escape($this->product->product_name); ?>
And my Bootstrap.php file:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initRoutes() {
$router = Zend_Controller_Front::getInstance()->getRouter();
include APPLICATION_PATH . "/configs/routes.php";
//$frontController = Zend_Controller_Front::getInstance();
$route = new Zend_Controller_Router_Route_Regex(
'(.+)',
array(
'controller' => 'products',
'action' => 'product'
),
array(
1 => 'nicelink',
),
'%s.html'
);
$router->addRoute('profileArchive', $route);
}
}
However, this solution has 1 major disadvantage: all other links such as
domain.com/contact
domain.com/about-us
are not working (probably due to the Bootstrap file).
How to fix the problem in order to make another links work and maintain current product links?
The issue is that you are matching all routes to product action in products controller. Probably you want to keep using the default routes in zend 1, which match "contact" and "about-us" to the corresponding actions in your default controller.
If you check "Zend_Controller_Router_Rewrite" function "addDefaultRoutes()" and "route()", you can see that the default routes will be checked after any custom ones.
The simplest solution, looking on what you are asking would be to match any routes that end with "-product":
$route = new Zend_Controller_Router_Route_Regex(
'(.+)\-product',
array(
'controller' => 'products',
'action' => 'product'
),
array(
1 => 'nicelink',
),
'%s.html'
);
In this case nicelink should take values "test" and "second-test" in your corresponding examples.

Set a generic layout for all modules in Zend framework 2

I'm working on a ZF2 Project, and I have some modules in my directories :
/module/module1
/module/module2
/module/module3
/module/module4
[...]
But, in each module I also have a specific layout, respectively :
/module/module1/view/layout/layout.phtml
/module/module2/view/layout/layout.phtml
/module/module3/view/layout/layout.phtml
/module/module4/view/layout/layout.phtml
My question is : How can I set a generic layout for all my modules without to have to modify each layout when I want.
Thank you
You can set the layout to be what ever you want in each modules config, just change the layout to be what ever you want:
module.config.php or inside getConfig()
'view_manager' => array(
// other stuff here..
'template_map' => array(
// use Applications layout instead
'layout/layout' => __DIR__ . '/../Application/view/application/layout/layout.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
Or you can set each module to selectively set it's layout in Module.php:
Module.php
/**
* Initialize
*/
public function init(ModuleManager $manager)
{
$events = $manager->getEventManager();
$sharedEvents = $events->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
/* #var $e \Zend\Mvc\MvcEvent */
// fired when an ActionController under the namespace is dispatched.
$controller = $e->getTarget();
$routeMatch = $e->getRouteMatch();
/* #var $routeMatch \Zend\Mvc\Router\RouteMatch */
$routeName = $routeMatch->getMatchedRouteName();
$controller->layout('application/layout/layout');
}, 100);
}

Zend routing without controller and action

There are given article URLs in a database (e.g. "article1", "article2", "article3").
When I type www.example.com/article1 I want to route to
controller: index,
action:index.
My route is:
//Bootstrap.php
public function _initRoute(){
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute('index',
new Zend_Controller_Router_Route('article1', array(
'controller' => 'index',
'action' => 'index'
))
);
}
But when I click on another link (functional before), I get www.example.com/article1 again.
Is there any way to do this route generally for all URLs in database? Something like:
$router->addRoute('index',
new Zend_Controller_Router_Route(':article', array(
'controller' => 'index',
'action' => 'index'
))
);
I usually set up an ini file instead of going the xml route or "new Zend_controller_Router_Route" way. In my opinion its a little easier to organize. This is how I do what you are looking for. I recommend that make some changes to your routing and not use a route of http://domain.com/article1 but more like http://domain.com/article/1. either way here is what I would do in your situation.
In your routes.ini file
routes.routename.route = "route"
routes.routename.defaults.module = en
routes.routename.defaults.controller = index
routes.routename.defaults.action = route-name
routes.routename.defaults.addlparam = "whatevs"
routes.routename.route = "route2"
routes.routename.defaults.module = en
routes.routename.defaults.controller = index
routes.routename.defaults.action = route-name
routes.routename.defaults.addlparam = "whatevs2"
routes.route-with-key.route = "route/:key"
routes.route-with-key.defaults.module = en
routes.route-with-key.defaults.controller = index
routes.route-with-key.defaults.action = route-with-key
In your bootstrap file
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
#... other init things go here ...
protected function _initRoutes() {
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini');
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->addConfig($config,'routes');
$front->setRouter($router);
return $router;
}
}
In your controller you can then do this
class IndexController extends Zend_Controller_Action {
public function routeNameAction () {
// do your code here.
$key = $this->_getParam('addlparam');
}
public function routeWithKeyAction () {
$key = $this->_getParam('key');
// do your code here.
}
}

Setup Zend Router with and without lang uri parameter

I'm wondering if anyone can help me with the next issue I have.
I want to be able to setup my project with multilanguage support with and without Uri lang flag, and also, with module structure.
I mean something like
http://mydomain/
http://mydomain/forum
http://mydomain/gallery
Navigate without lang uri parameter with the Zend_Locale + Zend_Translate default (en)
And also :
http://mydomain/es
http://mydomain/es/forum
http://mydomain/es/gallery
I've followed some tutos that I've found, but I still can't do so.
This is my current code :
I have zend _initRoute, _initLocale and _initTranslate setted on my bootstrap.php as follow:
protected function _initRoutes()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$module = new Zend_Controller_Router_Route_Module(
array(),
$front->getDispatcher(),
$front->getRequest()
);
$language = new Zend_Controller_Router_Route(
':lang',
array(
'lang' => 'es'
)
);
/**
* I didn't chain this route cause doesn't work as I expected,
* but this is how I want to be able to navigate.
*
**/
$default = new Zend_Controller_Router_Route(
':controller/:action/*',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$chainRoute = new Zend_Controller_Router_Route_Chain();
$chainRoute->chain($language)
->chain($module);
$router->addRoute('default', $chainRoute);
return $router;
}
/**
*
* Default locale: es_AR
*/
protected function _initLocale()
{
$local = new Zend_Locale();
$local->setDefault('es_AR');
Zend_Registry::set('Zend_Locale', $local);
}
/**
*
* Inisializacion de los lenguages y el Locale por default
*/
protected function _initTranslate()
{
$translate = new Zend_Translate(
'Array',
APPLICATION_PATH . "/langs/",
null,
array(
'scan' => Zend_Translate::LOCALE_DIRECTORY
)
);
Zend_Registry::set('Zend_Translate', $translate);
$translate->setLocale(Zend_Registry::get('Zend_Locale'));
}
I also register the next Language Plugin :
class MyApp_Controller_Plugin_Language extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$lang = $request->getParam('lang', null);
$locale = Zend_Registry::get('Zend_Locale');
$translate = Zend_Registry::get('Zend_Translate');
if ($translate->isAvailable($lang)) {
$translate->setLocale($lang);
$locale->setLocale($lang);
} else {
//throw new Zend_Controler_Router_Exception('Translation language is not available', 404);
$lang = $locale->getLanguage();
$locale->setLocale($lang);
$translate->setLocale($lang);
}
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->setParam('lang', $lang);
}
}
Also I've created my own Url helper extended by zend url helper which uses the 'Language_Action_Helper':
class Zend_View_Helper_MyUrl extends Zend_View_Helper_Url
{
protected function _getCurrentLanguage()
{
return Zend_Controller_Action_HelperBroker::getStaticHelper('Language')
->getCurrent();
}
public function myUrl($urlOptions = array(), $name = null, $reset = true, $encode = true)
{
$urlOptions = array_merge(
array(
"lang" => $this->_getCurrentLanguage()
),
$urlOptions
);
return parent::url($urlOptions, $name, $reset, $encode);
}
}
And then I've created an Anchor helper which uses my url Helper :
class Zend_View_Helper_Anchor extends Zend_View_Helper_Abstract
{
public function anchor
(
$anchorText,
$controller,
$action,
Array $params = array()
)
{
$front = Zend_Controller_Front::getInstance();
$defaultUrl = array(
'module' => $front->getRequest()->getModuleName(),
'controller' => $controller,
'action' => $action
);
if (!empty($params)) {
foreach ($params as $param => $value) {
$defaultUrl[$param] = $value;
}
}
// using my url helper
$url = $this->view->myUrl(
$defaultUrl,
null,
true
);
$anchor =<<<HTML
{$anchorText}
HTML;
return $anchor;
}
}
This is the Language Action helper to provide the language inside the controller used by my url helper.
class Controller_Helper_Language extends Zend_Controller_Action_Helper_Abstract
{
/**
*
* Get Current language
*
* #return mixed string|null
*/
public function getCurrent(){
if (!Zend_Registry::isRegistered("Zend_Locale"))
return null;
return Zend_Registry::get("Zend_Locale")->getLanguage();
}
/**
*
* Get translator
*
* #return mixed Zend_Translate|null
*
*/
public function getTranslator(){
if (!Zend_Registry::isRegistered("Zend_Translate"))
return null;
return Zend_Registry::get("Zend_Translate");
}
}
My final approach is with this structure, be able to set up standard routes like :
http://mydomain/forum/:id
http://mydomain/topic/:id
http://mydomain/section/:id
http://mydomain/user/:user
with language support.
How these routes must be configured to meet my needs?, I mean, I've tried to do something like :
// what may I do here? How do I chain this route with my language router
$topicRoute = new Zend_Controller_Router_Route(
'topic/:id',
array(
'module' => 'default',
'controller' => 'forum',
'action' => 'topic',
'id' => ':id'
),
array(
'id' => '^[0-9]$'
)
)
Also this router config bring me some problems with my navigation config.
When I set this router, and then navigate to /topic/id, when I hover any link given by the navigation.xml, always return the same URI given by this config.
http://mydomain/topic/id
Is anyone familiar with this?, Is this possible to do? Is any different way to do something like this? I've tried some different things which make me closer to my goal, but this is the most closer I could...
Thanks.
A better and cleaner way is to zend routes with hostname (eg. sub domains) take a look at following
http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname
this method is more easy and SEO friendly too.

Zend Framework - Custom defined routes overridden when adding Zend_Rest_Route

I'm creating an application that exposes a RESTful API in a module called api. For the other modules I created a little class that returns a Zend_Controller_Router_Rewrite object with custom defined routes:
$router = new Zend_Controller_Router_Rewrite();
foreach ($this->_modules as $module) {
if ($module === 'api') continue;
foreach ($this->_getConfigFiles($module) as $filename) {
$config = new Zend_Config_Ini($filename, 'routes');
$router->addConfig($config, 'routes');
}
}
return $router;
For the default module I have the following route:
[routes]
routes.default_index_index.type = Zend_Controller_Router_Route
routes.default_index_index.route = /
routes.default_index_index.defaults.module = default
routes.default_index_index.defaults.controller = index
routes.default_index_index.defaults.action = index
Now, in my Bootstrap file file I have the following:
$router = Shark_Module_Loader::getInstance()->getRouter();
$frontController->setRouter($router);
$frontController->getRouter()->removeDefaultRoutes();
$apiRoute = new Zend_Rest_Route($frontController, array(), array('api'));
$router->addRoute('rest', $apiRoute);
If I skip adding the rest route everything works fine for the default module, of course. But when I add the RESTful route the routes defined in the router are overridden(?), so the current route in the index action of the index controller of the default module ($this->getFrontController()->getRouter()->getCurrentRoute();) is an instance of Zend_Rest_Route. Thus, when trying to access a custom route defined in on of the route config files, lets say:
...
routes.default_pages_view.type = Zend_Controller_Router_Route
routes.default_pages_view.route = /view/:page
routes.default_pages_view.defaults.module = default
routes.default_pages_view.defaults.controller = pages
routes.default_pages_view.defaults.action = view
...
I get a 404 error saying that the request action (get) is not present.
I already went through the docs and didn't see any hint that suggests this behavior.
Any help and guidance will be appreciated.
There is no way to do this out of the box. (Check out this question)
You need to extend the Zend_Controller_Router_Route class. I've done it like this:
class Mauro_Controller_Router_Route_Method extends Zend_Controller_Router_Route {
protected $_method;
public function __construct($route, $defaults = array(), $reqs = array(), Zend_Translate $translator = null, $locale = null) {
list($this->_method, $route) = explode(' ', $route, 2);
parent::__construct($route, $defaults, $reqs, $translator, $locale);
}
public function match($path, $partial = false) {
$requestMethod = $this->getRequest()->getMethod();
$requestMethod = $this->getRequest()->getParam('method')
? strtoupper($this->getRequest()->getParam('method'))
: $requestMethod;
return $requestMethod == strtoupper($this->_method)
? parent::match($path, $partial)
: false;
}
protected function getRequest() {
return Zend_Controller_Front::getInstance()->getRequest();
}
}
You can then use it like this:
$router->addRoute( new Mauro_Controller_Router_Route_Method( 'GET /view/:page', array( 'controller' => 'pages', 'action' => 'view' ), array( 'page' => '/d+', ) ) );

Categories