简体   繁体   中英

Best practice for adding custom logic in Lumen/Laravel controller

I'm using Lumen (Laravel) to create an API for an online activity/campaign application which handles things like on-site registrations and gift redemptions for various events. Occasionally, there are certain events with very specific functionality required which need their own custom logic. I'm wondering how to best handle this custom code from an architecture/best practices standpoint.

Here's what I have: I have a route which calls a CustomCampaignController like so:

$router->group([
    'prefix' => 'v1'
], function () use ($router) {
    // ..... other routes for standard activities
    $router->post('customCampaigns', 'CustomCampaignController@runController');
});

Under App\\Http\\Controllers I've opened a directory to store classes for all custom activities. The customCampaigns route takes an activityId parameter whose value matches one of the activity classes. For example if the client posts activityId="MyCustomActivity" to customCampaigns, I would instantiate the following class: App\\Http\\Controllers\\Custom\\MyExampleActivity.

// app/Http/Controllers/CampaignController.php
public function runController(Request $request) {
    $className = 'App\\Http\\Controllers\\Custom\\' . $request->input('activityId');
    $customController = new $className;
    return $customController->run();
}

The custom controller would then do its thing and return the response

// app/Http/Controllers/Custom/MyCustomActivity.php
namespace App\Http\Controllers\Custom;

class MyCustomActivity
{
    public function __construct()
    {
        //
    }

    public function run()
    {
        // Custom logic here
        return response('Response');
    }
}

Is this a good approach or could it be considered an anti-pattern? Please let me know if there is another pattern for this type of problem.

I would prefer put the custom activity as the part of url. So, you will have something like this

$router->group([
  'namespace' => 'App\Http\Controllers\Custom',
  'prefix' => 'v1/customCampaigns'
], function () use ($router) {
  $router->post('myCustomActivity', 'MyCustomActivityController@methodName');
});

Using this format, you can map the endpoint directly into a specific controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM