Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 DI alias, same controller name in different modules

I have an application with 3 modules and route configs like below:

  • admin.domain.tld/[:controller[:/action]] => Admin
  • rest.domain.tld/[:controller[:/id]] => Rest
  • domain.tld/[:controller[:/action]] => Site

and set DI alias for all controller in each modules

REST Module DI Alias:

'alias' => array(
    'index' => 'Rest\Controller\IndexController',
    ...
),

Admin Module DI Alias:

'alias' => array(
    'index' => 'Admin\Controller\IndexController',
    ...
),

Site Module DI Alias:

'alias' => array(
    'index' => 'Site\Controller\IndexController',
    ...
),

As you see, some controllers has same name (eg: IndexController), but since zf2 merged config with LIFO behaviour, 'index' alias always from the last added module.

Application Config

'modules' => array('Rest','Admin', 'Site'),

when i access http://admin.domain.tld/ I expect index alias gives Admin\Controller\IndexController but since Site Module (registered last) has same alias for index it gives Site\Controller\IndexController

How to use different DI alias to match same controller name?

like image 505
Komang Avatar asked Aug 07 '26 17:08

Komang


1 Answers

Before the new view layer was merged into master, it was required to have aliases for controllers to behave correctly when resolving view scripts. Now this is not required anymore, it is even not recommended anymore to use aliases for controllers. The problem with aliasing is there is one alias for one FQCN, so your problem is directly related to this.

What you need to do is to remove aliases from the DI configuration and use explicit routes instead. The "magic" route [:controller[/:action]] is a bad practice and results in more problems than it can help you. So write some explicit routes and remove the aliases.

like image 148
Jurian Sluiman Avatar answered Aug 09 '26 14:08

Jurian Sluiman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!