Create Class Rules

You can create custom class rules with two main options: a generator class, or ad-hoc.

Create Generator Class

The generator class is the preferred method of adding new rules. Generator classes live in one location, so they promote good code maintenance.

Add A Generator

First decide where you will place your custom generators. For the purpose of this example, we will use app/Providers/RouteToClass/ to store all of our generators.

<?php

namespace App\Providers\RouteToClass;

use Zschuessler\RouteToClass\Generators\GeneratorAbstract;

class UserTypeGenerator extends GeneratorAbstract
{
    public function generateClassName()
    {
        // Use your own logic here to determine user type 
        $userType = 'admin';

        return 'user-' . $userType;
    }
}

As you can see above, all you need to do is extend the GeneratorAbstract class and implement a generateClassName method which returns a string. Simple!

Register Generator in Config

Now add the following line to the route2class.php configuration:

App\Providers\RouteToClass\UserTypeGenerator::class,

๐Ÿ“˜

See Included Example Generator

Example generator included in the package is here:

https://github.com/zschuessler/laravel-route-to-class/blob/master/src/Generators/FullRoutePath.php

Ad-Hoc Implementations

You aren't forced to use a class generator, although it's preferred. Simply call the addClass method of the package facade to add any number of custom classes.

The example below adds classes based on a route - but you can add these calls anywhere in your application (controllers, models, etc):

<?php
Route::get('/', function () {
    // Add static class as string
    Route2Class::addClass('homepage');

    // Add class from anonymous function
    Route2Class::addClass(function() {
        // Your custom logic goes here
        return 'my-anon-class-name';
    });

    return view('welcome');
});