title: Zend Framework 2 Get controller name from layout
body: <p>I have the follow routes to different controllers and actions, that all shows the same layout and different views, example:</p>
  
  <pre><code>http://&lt;my domain&gt;/controllername1/action1 
  http://&lt;my domain&gt;/controllername1/ 
  http://&lt;my domain&gt;/controllername2/action1
  http://&lt;my domain&gt;/controllername3/action1
  </code></pre>
  
  <p>How can I get the controller name that loads the Layout in the Layout code?, something that returns: "<strong>controllername1</strong>", "<strong>controllername2</strong>" or "<strong>controllername3</strong>"</p>
  
  <p>The goal is to identify in which section I'm of my site and make some customization in layout.</p>
  
  <p>I checked similar replies but are for old versions of Zend Framework. </p>
  
  <p><strong>Clarification:</strong>
  The idea is to get the controller name from the Layout code, not pass it from the controller code. Maybe isn't possible? Other answers are for older versions of ZendFramework (beta versions), and maybe is a more straightforward way now.</p>
  
  <p><strong>Edited: more information</strong></p>
  
  <p>I can set in my Module.php file the follow code on <strong>onBootstrap($e)</strong>:</p>
  
  <pre><code>public function onBootstrap($e)
  {
      // (...) Other code
  
      $application = $e-&gt;getParam('application');
      $viewModel = $application-&gt;getMvcEvent()-&gt;getViewModel();
  
      // Parsing URI to get controller name
      $viewModel-&gt;controllerName = trim($_SERVER['REQUEST_URI'],'/');
      if (substr_count($viewModel-&gt;controllerName, '/')) {
          $viewModel-&gt;controllerName = substr($viewModel-&gt;controllerName, 0, strpos($viewModel-&gt;controllerName, '/'));
       }
   }
  </code></pre>
  
  <p>And then from the Layout code use it as follow:</p>
  
  <pre><code>echo $this-&gt;layout()-&gt;controllerName;
  </code></pre>
  
  <p>The first problem is that the follow piece of code should be replaced with something (more "beautiful") using ZF2 functions to get Controller name:</p>
  
  <pre><code>(...)
  // Parsing URI to get controller name
  $viewModel-&gt;controllerName = trim($_SERVER['REQUEST_URI'],'/');
  if (substr_count($viewModel-&gt;controllerName, '/')) {
      $viewModel-&gt;controllerName = substr($viewModel-&gt;controllerName, 0, strpos($viewModel-&gt;controllerName, '/'));
  }
  </code></pre>
  
  <p>I want to avoid inject the Controller name from all controllers/actions: that is solved by using Module.php, but maybe is a more direct way.</p>
  
  <p>Thanks!</p>