Home » Php » php – Advice needed: Project Structure for Namespaced App Laravel

php – Advice needed: Project Structure for Namespaced App Laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am developing an app that has two name spaced differentiated folders.

Lets say

App/Http/Users/ and
App/Http/Drivers/

I have two api routes setup api.php and dapi.php.
The routes are also prefixed by localhost/api/foo and localhost/dapi/bar respectively.

Everything works ok but the issue is that there are some methods that I need to call for both. Such as save address info or call. Right now I have to make same controllers for both and duplicate a lot of code. What would be the best approach for this kind of project?

How to&Answers:

you should use traits

Traits are a mechanism for code reuse in single inheritance languages
such as PHP. A Trait is intended to reduce some limitations of single
inheritance by enabling a developer to reuse sets of methods freely in
several independent classes living in different class hierarchies. The
semantics of the combination of Traits and classes is defined in a way
which reduces complexity, and avoids the typical problems associated
with multiple inheritance and Mixins.

for example:

in your traite:

    trait SameMethods {
        function call() { /*1*/ }
        function saveAddress() { /*2*/ }
    }

.

namespace App\Http\Drivers;

        class Foo extends Controller{
            use SameMethods ;
            /* ... */
        }

.

namespace App\Http\Users;

        class Bar extends Controller{
            use SameMethods ;
            /* ... */
        }

Now you have these methods on your controllers.

another way is you have an another class for example ParentController extended from Controller that it contains same methods and foo and bar extends from this class

ParentController extends Controller {
    function call() { /*1*/ }
    function saveAddress() { /*2*/ }
}

.

namespace App\Http\Drivers;

        class Foo extends ParentController {

            /* ... */
        }

.

namespace App\Http\Users;

        class Bar extends ParentController {

            /* ... */
        }