controller,routing,zend-framework2 , zend2 adding another controller to application

zend2 adding another controller to application


Tag: controller,routing,zend-framework2

I'm working on a ZendFramework2.4-project. I just got started an filled the IndexController of a standard skeleton application with some code and thought of another controller in the same application.

No new modul, just a second Controller to keep code seperated.

Of course I read the documentation at Zend2: Routing and Controllers

But whatever I'm doing, I always get something like 404 not found. I get no route to the second controller.

When I read modul.config.php, I think, there's nothing to do in I right or wrong?

// The following is a route to simplify getting started creating
        // new controllers and actions without needing to create a new
        // module. Simply drop new controllers in, and you can access them
        // using the path /application/:controller/:action

But doing nothing but implementing the controller doesn't work too...

Is there something wrong with the documentation?

Maybe you have a hint...

Okay: I've tried to both of your examples you gave.

My module.config.php now looks like this:

 'controllers' => array(
    'invokables' => array(
        'Index' => 'Application\Controller\IndexController',
        'Am'    => 'Application\Controller\AmController'

'router' => array(
    'routes' => array(                  

        'home' => array(
            'type' => 'Literal',
            'options' => array(
                'route'    => '/',
                'defaults' => array(
                    'controller' => 'Index',
                    'action' => 'index'

        'arznei' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/[:controller][/:action][/:id]',
                'constraints' => array(
                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                'defaults' => array(
                    'controller' => 'Am',
                    'action'     => 'index',


Imho I think this should work for //myServer/ (first rule 'home') and for any other uri like //myServer/myController/myAction/25 .

But it doesn't.

For the second route I always get '404 object not found'. Maybe there is another option going wrong in the configuration of apache2. Seems the rewrite is incorrect in some way.

The rewrite module is loaded and enabled as far as I can see at the moment. I'm going to check out that issue.


You can have multiple controllers in a single module, but you need to set up your routing to identify when to use which controller. Since you have referenced Akrabat's album module in your question, I'll use it to illustrate:

The album module tutorial shows how to create four actions: indexAction, addAction, deleteAction and editAction; all in the same controller. Let's say, however, that since index deals with collections of albums and the other actions each manipulate a single album; we have decided to have two controllers: AlbumsController (which would include indexAction) and AlbumController (which would include the addAction, deleteAction and editAction).

In your module.config.php file, you will then need to invoke the second controller and create an alternate route to point to it:

 return array(
     'controllers' => array(
         'invokables' => array(
             'Album\Controller\Album' => 'Album\Controller\AlbumController',
             'Album\Controller\Albums' => 'Album\Controller\AlbumsController', // added second controller

     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'add',

             // add route to new controller
             'albums' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/albums[/:action]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                     'defaults' => array(
                         'controller' => 'Album\Controller\Albums',
                         'action'     => 'index',

 // ...


Passing params to an angular service from a controller?

I'm an angular newby. I'm hoping to pass params to a service that fetches data form a server depending on those params. for example, if I want to pass a book name string and then use it in the service to concatenate with the request url. The documentation does not...

Controller method: Contact form should render different page depending on where the form is used

I have a contact form on a special page dedicated to this form. The dedicated controller includes: def new @message = end def create @message = if @message.valid? MessageMailer.new_message(@message).deliver_now flash[:success] = "Thank you!" redirect_to contact_path else render 'new' end end Now I would also like to include this...

Reading from database in Laravel 4

How can I get the image url stored in my database and render it on the page in laravel 4?

Rails routing link to specific show

This question seems a little basic, but considering I have 'pages#show' with a show page with url 'history'. How could I add this specific show page to a link: = link_to 'History', pages_path(@?????) PD1: I would prefer avoid using :id since I tend to seed a lot of data, and...

Silex can't find Controller Class

project directory structure /composer.json /web/index.php /app/controller/IndexController.php composer.json { "require" : { "silex/silex": "*" }, "autoload": { "psr-0": { "": "./" } } } index.php require_once __DIR__.'/../vendor/autoload.php'; use Silex\Application; $app = new Application(); $app['debug'] = true; $app->get('/', 'App\\Controller\\IndexController::getIndex'); $app->run(); IndexController.php namespace App\Controller; use Silex\Application; class IndexController { public function getIndex(Application $app)...

How Do I call and pass data to a Directive from a Controller Angular

I have a QueueController.js which handles AJAX query. How do I pass the data from my CONTROLLER to my DIRECTIVE and show it to the Modal. Thanks. QueueController.js app.controller('QueueController', function($scope, $http, $interval, $modal) { $scope.Call = function(trans_id){ $http({ url: $locationProvider + 'query_stransaction', method: "GET", params: { trans_id: trans_id } }).success(function... MVC Routelink null controller parameter

I have two routes, the default one routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); I added another route, sometimes the parameter will by a string routes.MapRoute( name: "ByName", url: "{controller}/{action}/{name}", defaults: new { controller = "Home", action =...

USB3 Controller & Kinect 2

I recently updated a PC to Windows 8.1 in order to make it compatible to Kinect v2. It's an ASUS N53S with the following specs: CPU: Intel Core i7 - 2670QM (2.2GHz) RAM: 16 GB GPU: GEForce GT 550M USB3 Controller: Fresco Logic xHCI When running Kinect v2 Configuration Verifier...

RSpec 3 - Test controller action that does not have routes

I have a controller and there is an action within that controller. That action contains only a few lines of code and this method doesn't have any routes, as follows: class MyController < ApplicationController def action_a # an action does have routes ..some code.. end def action b #(an action...

Cannot implicity List into IEnumerable

My ViewModel public class ViewModelCT { public IEnumerable<SelectListItem> Tests { get; set; } public IEnumerable<string> SelectedTests { get; set; } public Course course { get; set; } } Controller public ActionResult Details(int id) { Course course = functionality.toCourse(functionality.GetCourseById(id)); List<SelectListItem> lsli = new List<SelectListItem>(); ViewModelCT vm = new ViewModelCT(); foreach (SchoolService.Test...

computed property that changes its value with action in Ember.js

I do have a controller that has an action {{loadRight}} that passes the current model to the controller when I click a button. When I first load the app, I also use firstElement computed property which pulls the first element from my model array. Basically what I want to do...

Laravel 5 form submit creates an error MethodNotAllowedHttpException

I'm using Laravel 5. When editing a form a get this error MethodNotAllowedHttpException There are a few posts but I think it may be code specific. I'd rather not use the resource route methods if possible. Route: Route::get('profile/edit', array('as' => 'admin.profile.edit', 'uses' => '[email protected]')); Route::post('profile/edit', array('as' => 'admin.profile.update', 'uses' =>...

Targeting $index from ng-repeat

How would I go about targeting this model in the controller? formData[$index].ID This is not working - $scope.getJob = function() { Employee.get({id: "" + $scope.formData[$index].ID}, function (data) { console.log(data); }) } ...

I don't understand routing

I am trying to learn a PHP framework. But I'm having some difficulties understanding some of the concepts of routing. I've chosen to use Flight. Their homepage shows: require 'flight/Flight.php'; Flight::route('/', function(){ echo 'hello world!'; }); Flight::start(); And I don't understand what they're using Flight::route... for. What am I missing?...

SAPUI5/OPENUI5 - Routing with Dialogs

I´m currently stuck with the combination of routing and dialogs. I have a view with list elements and when I click on an element in the list I want the Detail view to be shown in a Dialog (Popup). The thing is, I also want the ID of the list...

Open in same view controller as closed on (swift)

I am making a simple fact app (In swift) and all the facts are in separate view controllers and when the user closes the app, it all goes to the main page and you have to start from fact 1 again. I want to know how to save what view...

Where should I put Symfony third-party bundle's routing configuration?

I have SonataAdminBundle, SonataUserBundle and LiipImagineBundle installed in my Symfony 2 application. According to their installation instruction, I put their routing configuration in /app/config/routing.yml. _liip_imagine: resource: "@LiipImagineBundle/Resources/config/routing.xml" admin: resource: "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml" prefix: /admin _sonata_admin: resource: . type: sonata_admin prefix: /admin sonata_user: resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml' prefix: /admin...

calling the parent controller function in Ext.Ajax.request

I have a login Page which authenticates the user.On correct username and password it should hide the loginview and display the next view.When I call the function to do the same it gives an error saying "Uncaught TypeError: this.functionname is not a function.Here is my code for the same: startMain...

Node forward path request to another server

Currently have a website running a node server that handles all requests for and I created a completely separate wordpress blog on a separate server (running apache) that I would like served on a path like at IP address. The wordpress server doesn't share any code or...

Is it possible in laravel 5 to show a pretty url to the user, and a practical url to the app?

I have this url: I want my users to see this: Is this possible when using Route::resource('user', 'UserController');? If yes, how do I do it :) ? I still want my app to be able to see user/1/edit as I use it in my middleware to prevent unauthorized...

How to call this function for every controller in codeigniter

My situation is that, I have 20 controllers in my website, where I have a function like this. $this->lang->load("main", $this->session->userdata("lang_code")); How can I load this function in all the 20 controllers without adding it individually to the __constructor of every controller?...

How to get temperature value from DS18B20 voltage

I just connected DS18B20 temperature sensor to ADC of a device. But that device only shows voltage reading from ADC likve 1033 mV. But I want to get an actual temperature value from the voltage value. Is there any way to calculate or get the temperature value from voltage reading?...

Restrict laravel to open url that is not in route

I am Learning laravel now. Today I came across a problem that surprised me. I open this link in my browser: http://localhost/laravel/project/ch/resources/views/pages/blog.blade.php And I expect error 404. but it opens contains of this file. So, How to restrict laravel to do this. I want laravel to open only url mentioned...

Where is the syntax error in my rails app?

The following is my webhooks_controller.rb: class WebhooksController < ApplicationController before_action :auth_anybody! skip_before_filter :verify_authenticity_token def tx if params[:type] == "transaction" && params[:hash].present? AMQPQueue.enqueue(:deposit_coin, txid: params[:hash], channel_key: "satoshi") render :json => { :status => "queued" } end end And I'm getting the following error: webhooks_controller.rb:10: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)...

Rails category (or filter) links in same controller?

Having trouble understanding how using links_to filter content within the same controller in the rails view works. My code is below: # index.html.erb (link nav area) <nav> <%= link_to 'Daily Monitoring', root_path(:category => "dailymonitoring") %> <%= link_to 'Smoke Tests', root_path(:category => "smoketests") %> </nav> # index.html.erb (cont.) <ul id="results"> <%...

Why does this MVC action return a 404 response in IE11

I have written an mvc action that works in Chrome and Firefox but not in IE11. Using IE11 it returns a 404 response code. Controller: [HttpDelete] public ActionResult DeleteAction(int ActionID) { return Json(_Logic.DeleteAction(ActionID), JsonRequestBehavior.DenyGet); } Calling JS: Ajax_Proxy.DeleteAction = function (_actionID, successCallback, failureCallback) { return $.ajax({ type: "DELETE", datatype: 'json',...

Override one attribute in Rails strong params

Is there a way I can override one attribute yet still use strong parameters in Rails? Such as in the following example, if I wanted to override the person's name every time, but also use the person_params method. There has to be a better way than manually setting, right?...

Symfony/Twig how to render a Route set by anotation?

Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

No action was found on the controller that matches the request

Sorry for the lame question. I've already read all similar questions and still can't resolve my issue. I'm getting 'No action was found on the controller that matches the request' error when calling from ajax: $.ajax({ url: '/api/ToyEdit/Post/', dataType: "json", type: "POST", contentType: 'application/json; charset=utf-8', data: JSON.stringify({toyId: 1, toy: 'asd'}),...

Rspec test public controller method passing params to private controller method

This is my controller: class PlansController def use_new_card @user = User.find_by_id(new_card_params[:user_id]) if new_stripe_card ... end private def new_card_params params.permit(:user_id, :stripeToken) end def new_stripe_card{user_id:, customer_id: @user.stripe_customer_id, source: new_card_params[:stripeToken]}).new_card end end I'm trying to write a controller spec that tests that when the proper parameters are POST to the use_new_card...

How to add menus/ subtopics for meteor site?

I am new to meteor. I followed the tutorials and successfully making simple interfaces like below. I tried finding examples to add menus/ subtopics like this which does not reload the page when clicked, but I couldn't find any examples. Could you please give me an example how to do...

Angular $routeProvider and Controller As Syntax

Can anyone tell me if it is valid to use $routeProvider with Controller as syntax? I am having issues accessing <h1>{{}}</h1> from the controller where resides. angular.module('ucp.kick', ['ngRoute']).config(function($routeProvider, APP_BASE_URL) { return $routeProvider.when(APP_BASE_URL + 'kicks', { reloadOnSearch: false, navitem: true, name: 'Kicks', templateUrl: 'kick/partials/kick.html', controller: 'kick as KickController' }); });...

WebApi Routing not working for Post

My WebApiConfig has following routes // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Employee", action = "Get", id = RouteParameter.Optional } ); The Post WebApi method has got following Signatures [HttpPost] public IHttpActionResult Post(Employee emp) { ..... } When i try to call...

Re-transmission concept in TCP

Server sent data to client, but client didn't send ACK for the data . So once RTT completed , Server will resend data to client again .... like that how long it will try to send the data ? What is the maximum time server will try to send the...

Is bootstrap file a controller?

Sometimes, there are things that should be done at the very beginning of execution. And, I called it 'bootstrap' or 'initialization'. In bootstrap file, I usually disable the magic quotes at the runtime, set up the database adapter,defining paths, registering the autoloader, etc. Is it right to put that bootstrap...

Open page url in modal on a page (Facebook Photo URLs)

P.S. I am using html5Mode to remove '#' in routing in below scenario Removing the hashtag from AngularJS urls (# symbol) Consider I have two main pages.One is photos where thumbnails are provided and whose url is /someSlug/photos. Other is the url of a single photo '/someSlug/photos/somePhotoId' which shows a...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

How to access UrlHelper.Action or similar from within Global asax

I am trying to prepare a 301 redirect for a typo I made 'recieved' I am struggling to find a way of getting the url from the action and controller names. I am aware of UrlHelper.Action but it does not exist within Global.asax. How do I gain access to this...

Change resources path

I'm using Rails 4 I have a routes.rb file that looks like: resources :books However, I'd like the urls in the application to end up looking like /b/101 instead of /books/101. I realize I could go through and rename each resource path individually, but is there not a way to...

Sort a LINQ with another LINQ in MVC

Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

Select Mongoose Model Based on Express Route

I think this might be a basic question, but looking for the best approach. I'm building an express app that should route to one of four different Mongoose models depending on the route. Something like this: app.get('/:trial', function(req, res){ var trial = req.params.trial; trial.find(function(err, records) { if (err) res.send(err); res.json(records);...

Angular is giving me an injection unresolved error, but my controller isn't asking for any injections

I have a modal controller that is buggy, so I've been commenting out code to try to figure out the bug. Currently, my modal HTML partial is an empty div tag and my controller is a single console.log, with no arguments or parameters. The $ call only specifies the controller...

Grails: Carry forward params on hyperlink is clicked

How to carry forward the parameters when hyperlink is clicked? Here is my gsp code: <g:link class="grid_link" controller="user" action="delete" id="${}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure, want to delete?')}');">Delete</g:link> Here is my controller code: def delete() { try { def userInstance = User.get( //deleting the user //successful. redirect(action: "list",...

How to deal with extra “/” in phpleague route?

I am setting endpoints for my web application like this: $router = new League\Route\RouteCollection; function user_action (Request $request, Response $response) { // some logic . . . return $response; } $router->addRoute('GET', '/user', 'user_action'); /user endpoint works well. However when I use /user/ (extra slash in the end) I get a...

Why do I keep getting 'undefined method' when it's worked fine before?

My OrdersController is as follows below, but I keep getting this message: undefined method `listing_id=' for # Extracted source (around line #31): 29 30 31 @order.listing_id = Is there something I am doing incorrectly? Am following a tutorial so followed the instructions, then when it wasn't working decided to...

How to delete functions of previous instances of controller?

I have a simple angularjs controller referenced as someCtrl and it contains the following code: function testing() { console.log("Hello there."); } $document.on('click', function(e) { testing(); }); this.getView = function(value) { return viewService.getView(value); }; this.setView = function(value) { viewService.setView (value); }; this.destroy = function() { $state.reload('default_state'); }; When click event happens,...

$StateProvider Remove Child View Nesting

I am new to angular ui routing . I am creating a sample application and want to display parent and child view separately . I mean when parent item gets selected child view will be displayed and parent view would be hidden . If I add ui-view to parent view...

Route parameter with slash “/” in URL,routing,,,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

JavaFX : Button never sets a graphic

EDIT : A MCVE version of my code has been made to help debug it. It reproduces my bug. The purpose of my code is doing a Memory game. Which means that when it is your turn, you "open" a card, then another one. If they form a pair, they...

Resolve promise in service without callback in controller

I would like to ask/discuss wether this is good or bad practise - what are the pros and cons of making a service call insde a controller as clean and short as possible. In other words: not having a callback anymore but make use of the Angular binding principles of...