Zend 2 simple route not working correctly? - php

I have basic routes set like this (left only revelant part):
return array(
'controllers' => array(
'invokables' => array(
'Main\Controller\Login' => 'Main\Controller\LoginController',
'Main\Controller\Main' => 'Main\Controller\MainController',
'Main\Controller\Index' => 'Main\Controller\IndexController',
'Main\Controller\Candidate' => 'Main\Controller\CandidateController',
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Main\Controller\Index',
'action' => 'index',
),
),
),
'main' => array(
'type' => 'literal',
'options' => array(
'route' => '/ts',
'defaults' => array(
'controller' => 'Main\Controller\Main',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'candidates' => array(
'type' => 'literal',
'options' => array(
'route' => '/candidate',
'defaults' => array(
'controller' => 'Main\Controller\Candidate',
'action' => 'index'
),
),
'may_terminate' => true,
'child_routes' => array(
'add' => array(
'type' => 'literal',
'options' => array(
'route' => '/add'
),
'defaults' => array(
'action' => 'add'
),
),
),
),
),
),
),
),
So I believe the routes are:
/
/ts
/ts/candidate
/ts/candidate/add
Everything works smoothly except the last one /ts/candidate/add
I made some basic views, each returns simple
echo '<action_name>'
Where action_name is controller's action.
But each time, when I enter /ts/candidate/add, I got index action from
'Main\Controller\CandidateController'
instead of add action.
View structure looks like this:
view
-- errror
-- 404.phtml
-- index.phtml
-- layout
-- layout.phtml
-- login.phtml
-- main
-- candidate
-- index.phtml
-- add.phtml
-- main
-- index.phtml

You have the defaults for the child route in the wrong place, they should be inside options
'child_routes' => array(
'add' => array(
'type' => 'literal',
'options' => array(
'route' => '/add'
// defaults go here
'defaults' => array(
'action' => 'add'
),
),
),
),

Related

ZF2 route to controller

I have created a controller called "ActividadesPlanificadasController.php" and I have defined in my module.config the next routing but it is not work.
'publico/peticiones-incidencias-planificadas/actividades-planificadas' => array(
'type' => 'Literal',
'options' => array(
'route' => 'publico/peticiones-incidencias-planificadas/actividades-planificadas',
'defaults' => array(
'__NAMESPACE__' => 'Privado\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
//'route' => '/[:controller[/:action[/:id]]]',
'route' => '/[:controller[/:action][/:id/:system]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]*',
'system' => '[a-zA-Z][a-zA-Z0-9_-]*'
//'system' => '[0-9]*'
),
'defaults' => array(
),
),
),
),
),
These are my controllers ...
'controllers' => array(
'invokables' => array(
'Publico\Controller\Index' => Controller\IndexController::class,
'Publico\Controller\Login' => Controller\LoginController::class,
'Publico\Controller\NoAccess' => Controller\NoAccessController::class,
'Publico\Controller\ActividadesPlanificadas' => Controller\ActividadesPlanificadasController::class
),
),
Because I want to access to my controller with the next url: http://gnsys.local/publico/peticiones-incidencias-planificadas/actividades-planificadas
And I've got the next error ...
A 404 error occurred
Page not found.
The requested controller could not be mapped to an existing controller class.
Controller:
Publico\Controller\PeticionesIncidenciasPlanificadas(resolves to invalid controller class or alias: Publico\Controller\PeticionesIncidenciasPlanificadas)
No Exception available
What am I doing wrong?
Edit 1:
I have updated my module.config and it works with the route: http://gnsys.local/publico/actividades-planificadas
module.config:
'publico/actividades-planificadas' => array(
'type' => 'Literal',
'options' => array(
'route' => 'publico/actividades-planificadas',
'defaults' => array(
'__NAMESPACE__' => 'Publico\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
//'route' => '/[:controller[/:action[/:id]]]',
'route' => '/[:controller[/:action][/:id/:system]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]*',
'system' => '[a-zA-Z][a-zA-Z0-9_-]*'
//'system' => '[0-9]*'
),
'defaults' => array(
),
),
),
),
),
'controllers' => array(
'invokables' => array(
'Publico\Controller\Index' => Controller\IndexController::class,
'Publico\Controller\Login' => Controller\LoginController::class,
'Publico\Controller\NoAccess' => Controller\NoAccessController::class,
'Publico\Controller\ActividadesPlanificadas' => Controller\ActividadesPlanificadasController::class
),
),
But I want that my route to access to ActividadesPlanificadasController would be: http://gnsys.local/publico/peticiones-incidencias-actividades/actividades-planificadas
If I change my module.config to ...
'publico/peticiones-incidencias-planificadas/actividades-planificadas' => array(
'type' => 'Literal',
'options' => array(
'route' => 'publico/peticiones-incidencias-planificadas/actividades-planificadas',
'defaults' => array(
'__NAMESPACE__' => 'Publico\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
//'route' => '/[:controller[/:action[/:id]]]',
'route' => '/[:controller[/:action][/:id/:system]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]*',
'system' => '[a-zA-Z][a-zA-Z0-9_-]*'
//'system' => '[0-9]*'
),
'defaults' => array(
),
),
),
),
),
I've got the error
A 404 error occurred Page not found.
The requested controller could not be mapped to an existing controller class.
Controller: Publico\Controller\PeticionesIncidenciasPlanificadas(resolves to
invalid controller class or alias:
Publico\Controller\PeticionesIncidenciasPlanificadas)
No Exception available
What am I still doing wrong?
You point to a controller called 'Privado\Controller\Index' but your invokable is called 'Publico\Controller\Index'.
Change the namespace so it corresponds.
Privado -> Publico
or
Publico -> Privado
or add a controller for 'Privado\Controller\Index'
'invokables' => array(
'Privado\Controller\Index' => //your privado controller,
//...other controllers...
)
UPDATE
Make also sure you have an invokable controller class in the correct namespace. So if you register like this:
'invokables' => array(
'Privado\Controller\Index' => 'Privado\Controller\IndexController'
)
You need a controller class in a php file called IndexController.php in the folder Privado - Controller
- Privado
- Controller
- IndexController.php
And the class should have the correct name and namespace constant:
<?php
namespace = Privado\Controller;
class IndexController extends ... {
}

ZF2 Routing by Hostname works with other modules

I added a reseller subdomain on my myhost.com (reseller.myhost.com) and I use it for routing to my Reseller module. Read this question I posted before here: click here
My Reseller route config looks this:
'router' => array(
'routes' => array(
'Reseller' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'reseller.myhost.com',
'constraints' => array(
),
'defaults' => array(
'controller' => 'Reseller\Controller\Reseller',
'action' => 'index'
)
),
'may_terminate' => true,
'child_routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'__NAMESPACE__' => 'Reseller\Controller',
'controller' => 'Reseller',
'action' => 'index',
),
),
),
)
)
)
)
My createdAd route matches on reseller.myhost.com/createdAd but I expect routes from other modules not work on this reseller subdomain.
and here is my advertise route configuration
'router' => array(
'routes' => array(
'locate' => array(
'type' => 'segment',
'options' => array(
'route' => '/locate[/:cityName][/:CityId][/:CategoryId][/:categoryName]',
'constraints' => array(
),
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index',
),
),
),
'createAd' => array(
'type' => 'segment',
'options' => array(
'route' => '/createAd[/:subCategoryId]',
'constraints' => array(
),
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'createAd',
),
),
),
),
),
));
be notice that i want to advertise module work without subdomain and work normally and only reseller module work with subdomain
Why does this occur?
I understand from your question: you expect the createAd route not to work on the subdomain. So reseller.myhost.com/createdAd should not match instead you want a to match on the route without subdomain myhost.com/createdAd.
I would suggest that you should create a separate route definition for the Advertise module.
Your route config in Advertise module (module/Advertise/config/module.config.php)
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index'
)
),
)
'createAd' => array(
'type' => 'Literal',
'options' => array(
'route' => '/createAd',
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'createAd',
)
)
)
)
)
Your route config in Reseller module (module/Reseller/config/module.config.php)
'router' => array(
'routes' => array(
'Reseller' => array(
'type' => 'Hostname',
'options' => array(
'route' => ':reseller.myhost.com',
),
'may_terminate' => false,
'child_routes' => array(
'home' => array(
'type' => 'Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Reseller\Controller\Reseller',
'action' => 'index'
)
)
)
)
)
)
),
You can distinguish matches because of the subdomain.
The routes home and createAdd match the Advertise module without subdomain.
The route reseller.home matches the index in Reseller module within subdomain reseller.myhost.com.
Check for more details also the Hostname routing example here in the ZF2 documentation
You should have a "root" hostname for all your standard routes not on the subdomain route. Eg:
'router' => array(
'routes' => array(
'myhost' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'myhost.com',
),
),
),
),
Now you can add your 'createAd' route (and other routes) as a child route of the 'myhost' route. Eg:
'router' => [
'routes' => [
'myhost' => [
'child_routes' => [
'createAd' => array(
'type' => 'segment',
'options' => array(
'route' => '/createAd[/:subCategoryId]',
'constraints' => array(
),
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'createAd',
),
),
),
],
],
],
],

module config ViewJsonStrategy settings didn't work under child_route link

I don't know how can I explain my problem. I'm trying to get JSON response from one of my module that extend abstractrestfulcontroler. I have following module configuration
File: module.config.php
return array(
'controllers' => array(
'invokables' => array(
'TfwCommunication\\Controller\\TfwCommunication' => 'TfwCommunication\\Controller\\TfwCommunicationController',
'TfwCommunication\\Controller\\TfwChat' => 'TfwCommunication\\Controller\\TfwChatController',
'TfwCommunication\\Controller\\TfwContacts' => 'TfwCommunication\\Controller\\TfwContactsController',
'TfwCommunication\\Controller\\TfwMessage' => 'TfwCommunication\\Controller\\TfwMessageController',
'TfwCommunication\\Controller\\TfwUserMessageTemplates' => 'TfwCommunication\\Controller\\TfwUserMessageTemplatesController',
'TfwCommunicationControllerTfwUserMessageTemplates' => 'TfwCommunication\\Controller\\TfwUserMessageTemplatesController',
),
),
'router' => array(
'routes' => array(
'communication' => array(
'type' => 'Segment',
'options' => array(
'route' => '/communication',
'constraints' => array(
#'id' => '[0-9]+', # '[a-zA-Z][a-zA-Z0-9_-]*',
#'action'=>'[a-z][a-z0-9]*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwCommunication',
'action' => 'index',
#'id'=>'update',
#'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'actions'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/[:action[/]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwCommunication',
'action' => 'index',
),
),
),
'message' => array(
'type' => 'Segment',
'options' => array(
'route' => '/message',
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwMessage',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'read'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/[:id]',
'constraints' => array(
'id' => '[0-9]*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwMessage',
'action' => 'read',
),
),
),
'actions'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/[:action[/[:id]]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '.*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwMessage',
'action' => 'index',
),
),
),
'json-request-by-child-route'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/json-request-by-child-route[/:id]',
'constraints' => array(
'id' => '.*',
),
'defaults' => array(
'controller' => 'TfwCommunicationControllerTfwUserMessageTemplates',
),
),
),
),
),
),
),
'user-defined-templates'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/communication/message/user-defined-templates[/:id]',
'constraints' => array(
'id' => '.*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwUserMessageTemplates',
),
),
),
'user-defined-templates-direct-link'=>array(
'type' => 'Segment',
'options' => array(
'route' => '/user-defined-templates-direct-link[/:id]',
'constraints' => array(
'id' => '.*',
),
'defaults' => array(
'controller' => 'TfwCommunication\\Controller\\TfwUserMessageTemplates',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'tfwcommunication' => __DIR__ . DS.'..'.DS.'view',
),
'strategies' => array(
'ViewJsonStrategy',
),
),
);
Now following link is working - tfw.com.bd/communication/message/user-defined-templates/ OR tfw.com.bd/user-defined-templates-direct-link/
But following link will not work as expected (it says 404 controller not found) - tfw.com.bd/communication/message/json-request-by-child-route
Here tfw.com.bd indicating localhost.
Please note, I'm expected output as JSON format.
Also noted that, all I use here same controller. In some link/route it didn't work. I can't figure out the reason.
Can any ZF2 expert here who can explain the real reason behind the behavior.
Thanks
Finally I got this answer by myself. The above routing configuration didn't works due to default "action" define as "index". Zend seek "action" parameter, if found then it load that action. If not found it return "notFoundAction". So, in child route of above router defines "action" parameter. So, Zend din't go further when either it goes default "indexAction" or goes "notFoundAction".
Footnote, you need to avoid action parameter to get "JsonStrategy" works as expected. If you can't avoid action parameter in your router you can fix it by overloading "onDispatch" method of "AbstractRestfulController" controller.
Here is my code that works for me -
public function onDispatch(MvcEvent $e){
$routeMatch = $e->getRouteMatch();
if (! $routeMatch) {
/**
* #todo Determine requirements for when route match is missing.
* Potentially allow pulling directly from request metadata?
*/
throw new Exception\DomainException(
'Missing route matches; unsure how to retrieve action');
}
$request = $e->getRequest();
// Was an "action" requested?
#die('get_class($routeMatch): '.get_class($routeMatch).' #'.__LINE__.': '.__FILE__);
$action = $routeMatch->getParam('action', false);
if ($action) {
// Handle arbitrary methods, ending in Action
$method = static::getMethodFromAction($action);
if (! method_exists($this, $method)) {
if($method=='indexAction'){
$routeMatch->setParam('action', false);
return parent::onDispatch($e);
}
$method = 'notFoundAction';
}
$return = $this->$method();
$e->setResult($return);
return $return;
}
return parent::onDispatch($e);
}

Routing in Zend Framework 2

I'm trying to do some routing in Zend Framework 2, but it's not working.
The basics of the skeleton application are working, so I added a new module called User and the following code in the file \module\User\config\module.config.php
'controllers' => array(
'invokables' => array(
'User\Controller\User' => 'User\Controller\UserController',
),
),
'router' => array(
'routes' => array(
'login' => array(
'type' => 'Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'__NAMESPACE__' => 'User\Controller',
'controller' => 'User',
'action' => 'login',
),
),
),
'user_create' => array(
'type' => 'Literal',
'options' => array(
'route' => '/user/create',
'defaults' => array(
'__NAMESPACE__' => 'User\Controller',
'controller' => 'User',
'action' => 'create',
),
),
),
),
),
If I try to access the first route (/login), it works.
But the second route (/user/create) results in the error:
File:
F:\www\ZendVendas\library\Zend\Mvc\Router\Http\TreeRouteStack.php:313
Message:
Route with name "create" not found
If I do create a route without the controller name, it works:
'create' => array(
'type' => 'Literal',
'options' => array(
'route' => '/create',
'defaults' => array(
'__NAMESPACE__' => 'User\Controller',
'controller' => 'User',
'action' => 'create',
),
),
),
But I would want the route were "/user/create", and don't "/create".
I have searched for many topics, but can't see where is my mistake.
Appreciate any help ;)
Edit: ajusted code with suggestions of #Jurian
'router' => array(
'routes' => array(
'user' => array(
'type' => 'Literal',
'options' => array(
'route' => '/user',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'profile',
),
),
'child_routes' => array(
'login' => array(
'type' => 'Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'login',
),
),
),
'create' => array(
'type' => 'Literal',
'options' => array(
'route' => '/create',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'create',
),
),
),
),
),
),
),
You have to understand how routing works in Zend Framework 2. Routes have a name and some configuration. The structure looks as follows:
'router' => array(
'routes' => array(
'route_name_1' => array( /* config here */ ),
'route_name_2' => array( /* config here */ ),
'route_name_3' => array( /* config here */ ),
),
),
Here the route names are route_name_1 etc. If you assemble an url, you use that route name. So if route_name_1 has the url /foo/bar/baz, you can ask for the url of route_name_1 by using the url view helper:
echo $this->url('route_name_1'); // prints /foo/bar/baz
Your url /user/create is mapped to the route name user_create so to assemble this url, you need to pass on the route name:
echo $this->url('user_create'); // prints /user/create
CHILD ROUTES
There is also a concept of child routes. This can give you a route user which maps to /user and then this user route has a child create which maps to /create and as such the "total" route of create is /user/create. This can be configured as follows:
'router' => array(
'routes' => array(
'route_name_1' => array( /* config here */ ),
'route_name_2' => array(
/* config here */
'child_routes' => array(
'child_name_1' => array( /* config here */ ),
'child_name_2' => array( /* config here */ ),
),
),
),
),
Now, if you want to assemble an url for route_name_2 it just looks as above:
echo $this->url('route_name_1');
But if you need to assemble the url for child_name_1 you construct a "path" with a / between the name and its parent(s):
echo $this->url('route_name_1/child_name_1');
So although you can access the /user/create route fine with the route name you already have, you might want to use child routes as this gives you a more flexible routing system:
'router' => array(
'routes' => array(
'user' => array(
'type' => 'Literal',
'options' => array(
'route' => '/user/create',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'profile',
),
),
),
'child_routes' => array(
'login' => array(
'type' => 'Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'action' => 'login',
),
),
),
'create' => array(
'type' => 'Literal',
'options' => array(
'route' => '/create',
'defaults' => array(
'action' => 'create',
),
),
),
),
),
),
),
Then you have a route user which maps to a "profile". If you assemble user/create you go to /user/create and it uses the "createAction" from the user controller. The same hapens with user/login route.
I have found what I was doing wrong.
In one of my view files, there was a URL function pointing to the route /create.
It would be much helpful if Zend indicated the file with the invalid route, but, once I found the mistake, everything is working now.
'router' => array(
'routes' => array(
'login' => array(
'type' => 'Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'login',
),
),
),
'logout' => array(
'type' => 'Literal',
'options' => array(
'route' => '/logout',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'logout',
),
),
),
'user' => array(
'type' => 'Literal',
'options' => array(
'route' => '/user',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'profile',
),
),
'child_routes' => array(
'create' => array(
'type' => 'Literal',
'options' => array(
'route' => '/create',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'create',
),
),
),
'edit' => array(
'type' => 'Literal',
'options' => array(
'route' => '/edit',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'edit',
),
),
),
),
),
),
),
Thank you for the help!

Zend\Mvc\Router\Http\Method and child routes

i have defined two routes, /shoppingcart/ and a child route /shoppingcart/add/ which should only be available for POST requests.
'routes' => array(
'shoppingcart' => array(
'type' => 'literal',
'options' => array(
'route' => '/shoppingcart/',
'defaults' => array(
'controller' => 'ShoppingcartController',
'action' => 'shoppingcart',
),
),
'may_terminate' => true,
'child_routes' => array (
'add-product' => array(
'type' => 'method',
'options' => array(
'verb' => 'post',
'route' => 'add/',
'defaults' => array(
'controller' => 'ShoppingcartController',
'action' => 'addProductToShoppingcart',
),
),
),
)
),
)
The route /shoppingcart/ works fine. The child route /shoppingcart/add/ does not work(404 error with POST and GET).
When i change the type from method to literal and remove the verb key it works.
How can i use Zend\Mvc\Router\Http\Method in the child route?
You need to set may_terminate true for your child route.
Also, you mention route failing for GET, which it will if you only set the verb to post, if you want to allow get too, the verb should be get,post
Edit: after a little experimenting, it turns out my understanding was wrong, the Method type needs to be placed as parent of the route it's protecting....
'routes' => array(
'shoppingcart' => array(
'type' => 'literal',
'options' => array(
'route' => '/shoppingcart/',
'defaults' => array(
'controller' => 'ShoppingcartController',
'action' => 'shoppingcart',
),
),
'may_terminate' => true,
'child_routes' => array (
'add-product' => array(
'type' => 'method',
'options' => array(
'verb' => 'get,post',
),
'child_routes' => array(
// actual route is a child of the method
'form' => array(
'may_terminate' => true,
'type' => 'literal',
'options' => array(
'route' => 'add/',
'defaults' => array(
'controller' => 'ShoppingcartController',
'action' => 'addProductToShoppingcart',
),
),
),
),
),
),
),
),

Categories