⊗ppMVUFmRP 8 of 35 menu

Parameters in Routes in MVC in PHP

In the previous lesson, our routes had fixed addresses. In fact, the routing mechanism is more complex - it is possible to make a part of the page URI fall into named parameters, which are then available in the controller.

Let's say, for example, our addresses look like this: /test/param1/param2/, where param1 and param2 are arbitrary strings. At the same time, we want addresses of this type to be handled by one controller action. To do this, you should come up with a parameter name and put a colon before it, like this:

<?php use \Core\Route; return [ new Route('/test/:var1/:var2/', 'page', 'act'), ]; ?>

In our case, it will turn out that all requests of the form /test/parameter1/parameter2/ will go to the action act. At the same time, the first parameter of this action will receive an associative array with parameters: the text that will be in place of the first parameter, will go into the array element with the key 'var1', and the text of the second parameter - into 'var2'.

Let's say, for example, the following is typed in the address bar: /test/eee/bbb/. Let's see what the first parameter of the action will contain:

<?php namespace Project\Controllers; use Core\Controller; class PageController extends Controller { public function act($params) { var_dump($params); // ['var1' => 'eee', 'var2' => 'bbb'] } } ?>

Create a controller NumController, and in it - an action sum. Let this action handle addresses of the following type: /nums/:n1/:n2/:n3/, where the parameters will be some numbers. Make it so that the sum of the passed numbers is displayed on the screen.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline