需要建议:命名空间应用程序的项目结构 Laravel

Advice needed: Project Structure for Namespaced App Laravel

我正在开发一个应用程序,它有两个名称间隔不同的文件夹。

让我们说

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

我有两个 api 路由设置 api.phpdapi.php。 路由也分别以 localhost/api/foolocalhost/dapi/bar 为前缀。

一切正常,但问题是我需要同时调用一些方法。例如保存地址信息或呼叫。现在我必须为两者制作相同的控制器并复制大量代码。这种项目的最佳方法是什么?

你应该使用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.

例如:

在你的特质中:

    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 ;
            /* ... */
        }

现在你的控制器上有了这些方法。

另一种方法是你有另一个 class 例如 ParentController 从 Controller 扩展,它包含相同的方法,foo 和 bar 从这个 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 {

            /* ... */
        }