PHPackages                             webx/routes - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. webx/routes

ActiveLibrary

webx/routes
===========

2.0.14(7y ago)127411MITPHP

Since Mar 24Pushed 7y ago1 watchersCompare

[ Source](https://github.com/niclaslindberg/webx-routes)[ Packagist](https://packagist.org/packages/webx/routes)[ RSS](/packages/webx-routes/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (4)Versions (67)Used By (1)

WebX-Routes - A PHP controller framework
========================================

[](#webx-routes---a-php-controller-framework)

Main features and design goals of webx-routes:

- Simplicity - Easy to follow request/response routes to business logic in a natural hierarchical model.
- Scalability - never load unnecessary files
- Dependency injection (IOC) everywhere.
- Testability - clear separation of view- and business objects by glueing it all together.

Getting started
---------------

[](#getting-started)

In `composer.json` add:

```
 {
    "require" : {
        "webx/routes" : "major.minor.patch"
    }
 }
```

Writing your first Routes index.php `public/index.php`
------------------------------------------------------

[](#writing-your-first-routes-indexphp-publicindexphp)

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Response;

    require_once "../vendor/autoload.php"; // $_SERVER["DOCUMENT_ROOT"] points to 'public' folder.

    RoutesBootstrap::run(function(Response $response) {
        $response->typeJson([
            "user" =>
                ["name" => "Mr. Andersson"]
            ]
        ]);
        $response->data(1998,"user.popular"); //Merges the data into 'user.popular'
    });
```

Will generate JSON response:

```
    {
        "user" : {
            "name" => "Mr. Andersson",
            "popular" => 1998
        }
    }
```

Built-in ResponseTypes in Routes
--------------------------------

[](#built-in-responsetypes-in-routes)

Routes supports the following ResponseTypes out of the box

- `JsonResponse` Renders data as Json (Default ResponseType).
- `TemplateResponseType` Renders data with a template (Twig)
- `RawResponseType` Renders data as is.
- `DownloadResponseType` Renders data as a downloadable file.
- `RedirectResponseType` 301 or 302 redirect to a different url.
- `FileContentResponseType` Sends a file's content to browser with auto detecting content-type.

Routing in Routes
-----------------

[](#routing-in-routes)

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Routes;
    use WebX\Routes\Api\Response;

    RoutesBootstrap::run(function(Routes $routes) {

        $routes->onSegment("api",function(Routes $routes) {

            $routes->onMatch("v(?P\d+)$",function(Routes $routes,$version) {
                $routes->load("api_v{$version}");                      // $version from RegExp

            })->onAlways(Response $response) {
                $response->typeJson(["message"=>"Not a valid API call"]);
            });

        })->onAlways(function(Response $response){
            $response->typeRaw();
            $response->data("Sorry, page not found.");
            $response->status(404);

        })
    });
```

Routing in Routes - with url parameters example
-----------------------------------------------

[](#routing-in-routes---with-url-parameters-example)

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Routes;
    use WebX\Routes\Api\Response;

    RoutesBootstrap::run(function(Routes $routes) {
        $routes->onAlways(function(Response $response, $myParam="default") {
            $response->typeRaw($myParam);
        }
    });
```

Will render:

- `hello` for request on `/hello`
- `default` for request on `/`

### Route switches:

[](#route-switches)

Route switches are evaluated top-down. If a route-switch is executed no further switches, in same the scope, are evaluated and executed.

The following route switches are supported

- `onAlways($action)` Executes without evaluation.
- `onTrue($expression,$action)` Executes if `$expression` evaluates to `true`
- `onSegment("url-segment",$action)` Evaluates the current url segment (complete url exploded by `/`). Within a route-switch match the current url-segment will advance one position.
- `onMatch("reg-exp",$action)` Evaluates the reg-exp against a string (url is default). Matched parameters in the reg-exp will be used if the same variable name is used in the `$action`;

Using Twig
----------

[](#using-twig)

`page.twig`

```

            Welcome {{user.name}}
            Your input was {{input}}

```

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Response;
    use WebX\Routes\Api\Request;

    RoutesBootstrap::run(function(Response $response, Request $request) {
          $response->typeTemplate()->id("page");
          $response->data(["name"=>"Mr. Andersson"],"user");
          $response->data($request->parameter("input"), "input");
    });
```

Reading input
-------------

[](#reading-input)

Routes provides a unified and type-safe way to read request input from query parameters and json- form-encoded requests.

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Response;
    use WebX\Routes\Api\Request;

    RoutesBootstrap::run(function(Response $response, Request $request) {
          $reader = $request->reader(Request::INPUT_AS_JSON);
          $response->typeJson(["greeting"=>"Hello, {$reader->asString("user.name")}"]);
    });
```

### Configuring Twig

[](#configuring-twig)

Load a configuration `changetwig` (can be any name) at Bootstrap time.

Example: To change Twigs tag-delimeters to `{{{` and `}}}` (To simplify mixed Angular and Twig in the same page).

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Routes;
    use WebX\Routes\Api\Response;

    RoutesBootstrap::run([function(Routes $routes) {

        $routes->onAlways(function(Response $response) {
              $response->templateType()->id("page");
              $response->data(["name"=>"Mr. Andersson"],"user");
        })

    },"changetwig"]);
```

Override the setting for `TemplateResponseType` to add a configurator for Twig `config/changetwig.php`:

```
    return [
        "responseTypes" => [
            "WebX\\Routes\\Api\\ResponseTypes\\TemplateResponseType" => [
                "config" => [
                    "configurator" => function(Twig_Environment $twig) {
                        $lexer = new Twig_Lexer($twig, array(
                            'tag_variable'  => array('{{{', '}}}')
                        ));
                        $twig->setLexer($lexer);
                    },
                    "options" => [    // Passed as second argument to Twig_Environment
                        "cache" => "/tmp/twig_cache"
                    ]
                ]
            ]
        ]
    ]
```

Loading configurations and the IOC container
--------------------------------------------

[](#loading-configurations-and-the-ioc-container)

All logic, in Routes, is executed in `actions`. An action can be either a:

- `\Closure`
- `string` (In format "ControllerClass#method")

To support lazy loading of configurations Routes allows actions to be defined as an `array` in the format: `[$action,"config1","config2","configN"]`

`src/MyBusiness/Impl/Services/AdminService.php`

```
    use MyBusiness\Api\Services\IAdminService;

    class AdminService implements IAdminService {
        public function __construct() {}

        public function countAdmins() {
            return 3;
        }
    }
```

`config/admin.php`:

```
    use MyBusiness\Impl\Services\AdminService;

    return [
        "ioc" => [
            "register" => [
                [AdminService::class]
            ]
        ]
    ]
```

```
    use WebX\Routes\Api\RoutesBootstrap;
    use WebX\Routes\Api\Routes;
    use WebX\Routes\Api\Response;
    use MyBusiness\Api\Services\IAdminService;

    RoutesBootstrap::run(function(Routes $routes) {

        $routes->onSegment("admin",[function(Response $response, IAdminService $adminService) {
              $response->data($adminService->countAdmins(),"count");
        },"admin"]);

        // The admin-configuration is only loaded if routes matched the `admin` segment.
    });
```

\#Config file anatomy The config files, that may be loaded at any level, are normal php files that are expected to return an `array`.

Minimal config file (that does nothing):

```

```

Ioc container
-------------

[](#ioc-container)

The [WebX-Ioc container](https://github.com/niclaslindberg/webx-ioc) is embedded in the WebX-Routes framework. WebX-Routes supports dynamic registration / static invokation of services in the config `ioc` section.

Dynamically register a service with the WebX-Ioc container. `config/someconfig.php`

```
