{"metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","params":[],"results":{"codes":[]},"settings":""},"next":{"description":"","pages":[]},"title":"Controller","type":"basic","slug":"mvc-controller","excerpt":"","body":"# Controller\n\nMVC can be metaphorically related to a TV. You have various channels, with different information on them supplied by your cable provider (the model). The TV screen displays these channels to you (the view). **You pressing the buttons on the remote controls affects what you see and how you see it (the controller)**. -<a href=\"http://stackoverflow.com/questions/2626803/mvc-model-view-controller-can-it-be-explained-in-simple-terms#answer-2626813\">Tilo Mitra</a>\n\n## Index:\n- [Generate New Controller](#generate-new-controller)\n- [Basic Routing](#basic-routing)\n- [Middleware](#middleware)\n\n<a name=\"generate-new-controller\"></a>\n# Generate New Controller\n\nRun this to your console\n```shell\nphp brood app:controller Ticket main\n```\n\nThe above console command creates a ``TicketController`` under the ``main`` module.\n\nThere must be a file located at ``app/main/controllers/TicketController.php``\n\n<a name=\"basic-routing\"></a>\n# Basic Routing\n\nLet us say we're using a different domain that points to ``main`` module, example ``http://www.flavoredtickets.com``, and we want to have a new route, the route file must be located at ``app/main/routes.php``\n\n```php\nRoute::addGet('/new', [\n    'controller' => 'Ticket',\n    'action' => 'new',\n]);\n\nRoute::addPost('/create', [\n    'controller' => 'Ticket',\n    'action' => 'create',\n]);\n\nRoute::addPost('/update/{id}', [\n    'controller' -> 'Ticket',\n    'action' => 'update',\n]);\n\nRoute::any('/delete/{id}', [\n    'controller' => 'Ticket',\n    'action' => 'delete',\n]);\n```\n\n|Verb          |URI           |Desc                                                                                               |\n|--------------|--------------|---------------------------------------------------------------------------------------------------|\n|``GET``       | /new         |The ``TicketController`` will be instantiated and the function ``new()`` will be called            |\n|``POST``      | /new         |The ``TicketController`` will be instantiated and the function ``create()`` will be called         |\n|``POST``      | /update/1    |The ``TicketController`` will be instantiated and the function ``update($id)`` will be called      |\n|``GET`` or ``POST``       | /delete/1    |The ``TicketController`` will be instantiated and the function ``delete($id)`` will be called      |\n\nThe above table shows you how the request and uri processes along the Controller class. <a target=\"_blank\" href=\"/docs/supporting-structure-routing\">To know more about routing, click here.</a>\n\n\n---\n\n<a name=\"middleware\"></a>\n# Middleware\n\n```php\n# namespace/use code here\n\nclass TicketController extends Controller\n{\n    public function initialize()\n    {\n        $this->middleware('csrf', [\n            'only' => [\n                'create',\n            ],\n        ]);\n    }\n\n    # some functions below\n}\n```\n\nThe code above shows how to call a middleware, Phalcon uses ``__construct()`` as final function in it, however they added a new function called ``initialize()``, this function was called after the instantiation of the class.\n\nWe have a parent function called ``$this->middleware($alias, $options = [])``, the alias is located at ``project-name/config/app.php`` under ``midlewares``.\n\nWe're calling ``'csrf'`` key, if the dispatched route points to ``create()`` function. The class will be called and it is located at ``project-name/components/Middleware/CSRF.php`` that has this kind of code:\n```php\n<?php\nnamespace Components\\Middleware;\n\nuse Clarity\\Exceptions\\AccessNotAllowedException;\n\nclass CSRF implements \\League\\Tactician\\Middleware\n{\n    public function execute($request, callable $next)\n    {\n        if ( $request->isPost() ) {\n\n            if ( security()->checkToken() === false ) {\n\n                # - throw exception or redirect the user\n                # or render a content using\n                # View::take(<resources.view>);exit;\n\n                throw new AccessNotAllowedException('Token mismatch, what are you doing?');\n            }\n        }\n\n        return $next($request);\n    }\n}\n```\n\nCan you guess the above code?\n\nIt validates your request if it is POST and it validates the csrf token from the form if it is correct, else it will throw an ``AccessNotAllowedException``","updates":[],"order":1,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"_id":"56d648da70eba32d006060b0","user":"56c1105874f0b417004baadc","createdAt":"2016-03-02T01:58:50.917Z","project":"56c111095abfe40d00be875a","__v":30,"category":{"sync":{"isSync":false,"url":""},"pages":["56d6449db939870b00512c63","56d648d270eba32d006060ae","56d648da70eba32d006060b0","56d648e870eba32d006060b2","56e23cde7d54ba0e00463568"],"title":"Modular-MVC","slug":"modular-mvc","order":2,"from_sync":false,"reference":false,"_id":"56c4275048213b1700af6e33","createdAt":"2016-02-17T07:54:56.500Z","project":"56c111095abfe40d00be875a","version":"56c111095abfe40d00be875d","__v":5},"parentDoc":null,"githubsync":"","version":{"version":"1.3.0","version_clean":"1.3.0","codename":"","is_stable":true,"is_beta":false,"is_hidden":false,"is_deprecated":false,"categories":["56c1110a5abfe40d00be875e","56c413a254b6030d00ec299d","56c4275048213b1700af6e33","56c42826c0c4630d004e86cb","56c4282cbc41330d009f2607","56c4284ad1f6d91700d3697e","56e271c195d1c60e00a969ee"],"_id":"56c111095abfe40d00be875d","releaseDate":"2016-02-14T23:43:05.566Z","__v":7,"createdAt":"2016-02-14T23:43:05.566Z","project":"56c111095abfe40d00be875a"}}
# Controller MVC can be metaphorically related to a TV. You have various channels, with different information on them supplied by your cable provider (the model). The TV screen displays these channels to you (the view). **You pressing the buttons on the remote controls affects what you see and how you see it (the controller)**. -<a href="http://stackoverflow.com/questions/2626803/mvc-model-view-controller-can-it-be-explained-in-simple-terms#answer-2626813">Tilo Mitra</a> ## Index: - [Generate New Controller](#generate-new-controller) - [Basic Routing](#basic-routing) - [Middleware](#middleware) <a name="generate-new-controller"></a> # Generate New Controller Run this to your console ```shell php brood app:controller Ticket main ``` The above console command creates a ``TicketController`` under the ``main`` module. There must be a file located at ``app/main/controllers/TicketController.php`` <a name="basic-routing"></a> # Basic Routing Let us say we're using a different domain that points to ``main`` module, example ``http://www.flavoredtickets.com``, and we want to have a new route, the route file must be located at ``app/main/routes.php`` ```php Route::addGet('/new', [ 'controller' => 'Ticket', 'action' => 'new', ]); Route::addPost('/create', [ 'controller' => 'Ticket', 'action' => 'create', ]); Route::addPost('/update/{id}', [ 'controller' -> 'Ticket', 'action' => 'update', ]); Route::any('/delete/{id}', [ 'controller' => 'Ticket', 'action' => 'delete', ]); ``` |Verb |URI |Desc | |--------------|--------------|---------------------------------------------------------------------------------------------------| |``GET`` | /new |The ``TicketController`` will be instantiated and the function ``new()`` will be called | |``POST`` | /new |The ``TicketController`` will be instantiated and the function ``create()`` will be called | |``POST`` | /update/1 |The ``TicketController`` will be instantiated and the function ``update($id)`` will be called | |``GET`` or ``POST`` | /delete/1 |The ``TicketController`` will be instantiated and the function ``delete($id)`` will be called | The above table shows you how the request and uri processes along the Controller class. <a target="_blank" href="/docs/supporting-structure-routing">To know more about routing, click here.</a> --- <a name="middleware"></a> # Middleware ```php # namespace/use code here class TicketController extends Controller { public function initialize() { $this->middleware('csrf', [ 'only' => [ 'create', ], ]); } # some functions below } ``` The code above shows how to call a middleware, Phalcon uses ``__construct()`` as final function in it, however they added a new function called ``initialize()``, this function was called after the instantiation of the class. We have a parent function called ``$this->middleware($alias, $options = [])``, the alias is located at ``project-name/config/app.php`` under ``midlewares``. We're calling ``'csrf'`` key, if the dispatched route points to ``create()`` function. The class will be called and it is located at ``project-name/components/Middleware/CSRF.php`` that has this kind of code: ```php <?php namespace Components\Middleware; use Clarity\Exceptions\AccessNotAllowedException; class CSRF implements \League\Tactician\Middleware { public function execute($request, callable $next) { if ( $request->isPost() ) { if ( security()->checkToken() === false ) { # - throw exception or redirect the user # or render a content using # View::take(<resources.view>);exit; throw new AccessNotAllowedException('Token mismatch, what are you doing?'); } } return $next($request); } } ``` Can you guess the above code? It validates your request if it is POST and it validates the csrf token from the form if it is correct, else it will throw an ``AccessNotAllowedException``