Before everything, I'm using Laravel 6 and PHP 7.2.
Alright. I have various models on which I can do the same action. For the of being DRY, I thought of the following idea:
On each model I'll implement an interface, and I'll put the actual implementation for handling the action in a single invokable controller.
The thing is I don't know how to have a working model route binding with such implementation.
To make my question easier for understanding here is some code snippets:
- Models
class Post extends Model implements Actionable { /* attributes, relationships, etc. */ }
class Comment extends Model implements Actionable { /* attributes, relationships, etc. */ }
class User extends Model implements Actionable { /* attributes, relationships, etc. */ }
- Controllers
class DoActionOnActionable extends Controller
{
public function __invoke(Actionable $actionable, Request $request) {
// implementation
}
}
I know for Laravel to do the model route binding, it does need to know what model to bind to this I've made the DoActionOnActionable
controller abstract and created 3 other controllers in the same file (which kinda annoys me because it's mostly repetitive):
class DoActionOnUser extends DoActionOnActionable
{
public function __invoke(User $user, Request $request) {
parent::__invoke($user, $request);
}
}
class DoActionOnPost extends DoActionOnActionable
{
public function __invoke(Post $post, Request $request) {
parent::__invoke($post, $request);
}
}
class DoActionOnComment extends DoActionOnActionable
{
public function __invoke(Comment $comment, Request $request) {
parent::__invoke($comment, $request);
}
}
- Routes
Route::post('/users/{user}/actions', 'DoActionOnUser');
Route::post('/posts/{post}/comments/{comment}/actions', 'DoActionOnComment');
Route::post('/posts/{post}/actions', 'DoActionOnPost');
The issue is when I send a request to these routes, it takes as much time to respond that I cancel the request. So, I think something is wrong and it's not working as I expected.
I appreciate anything that helps me understand my implementation issue or a better solution to my problem (being DRY).