Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use statement for child classes

I have a Controller class in which I have to use several namespaces like :

<?php

use Respect/Validation/Validator;
use Blah/blah/Foo;

class Controller {}

Now what I want that in every controller files that extends my Controller class, I do not have to write the use statements again and again.

This is something I want similar to what Laravel has done in his alias section.

How would I achieve this thing ? So for example when I do :

<?php
class HomeController extends Controller {
   public function index()
   {
       $data = '';
       Validator::arr($data); // Validator not found
   }

}
like image 460
Raheel Avatar asked May 13 '26 09:05

Raheel


1 Answers

This is unfortunately what you would have to do if using static methods. You could also have a Controller method (the constructor even) to inject the validator into the class, which the child classes can then use. You would the use public instance variables on the validator.

The benefit is that you do not need to specify the NS for your dependencies again and, especially so, your code is cleaner since you do not have a hard dependency on the Validator class.

like image 174
James Dunne Avatar answered May 15 '26 23:05

James Dunne