gpt4 book ai didi

php - 需要建议 : Project Structure for Namespaced App Laravel

转载 作者:行者123 更新时间:2023-12-04 16:55:31 26 4
gpt4 key购买 nike

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

可以说
App/Http/Users/App/Http/Drivers/
我有两个 api 路由设置 api.phpdapi.php .
路由也以 localhost/api/foo 为前缀和 localhost/dapi/bar分别。

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

最佳答案

你应该使用 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 ;
/* ... */
}

现在你的 Controller 上有了这些方法。

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

/* ... */
}

关于php - 需要建议 : Project Structure for Namespaced App Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60289100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com