
php 中的属性允许您直接使用元数据注释代码元素,从而简化了代码配置,从而可能减少 laravel 等框架中的样板文件。然而,与任何功能一样,属性可能会被过度使用或误用,从而导致控制器混乱和代码难以维护。
在这篇文章中,我们将探索以增强代码清晰度的方式使用属性的最佳实践。我还将提供一个“该做和不该做”的表格,其中包含每次比较的示例,突出显示属性工作良好的场景以及可能不工作的场景。
这是定义和使用属性来提供一些上下文的快速示例:
#[attribute]
class mycustomattribute {
public function __construct(public string $description) {}
}
#[mycustomattribute("this is a test class")]
class myclass {
#[mycustomattribute("this is a test method")]
public function mymethod() {}
}
下表总结了最佳实践和常见陷阱:
| do’s | don’ts |
|---|---|
| use attributes for standard, repetitive configurations (e.g., http methods, caching). | don’t overload attributes with complex configurations or conditional logic. |
| leverage attributes for metadata rather than core application logic. | avoid embedding business logic or intricate rules within attributes. |
| apply attributes for simple, reusable annotations (e.g., #[throttle], #[cache]). | don’t try to replace laravel’s route files entirely with attribute-based routing. |
| cache attribute-based reflections when possible to improve performance. | don’t rely solely on attributes for configurations that need flexibility or change often. |
| document your attributes, so team members understand their purpose and usage. | avoid using attributes for configurations where traditional methods work better (e.g., middleware settings). |
让我们通过具体示例深入了解每个比较。
立即学习“PHP免费学习笔记(深入)”;
属性非常适合不需要复杂逻辑的标准配置。以下是三个很好的例子:
#[attribute]
class route {
public function __construct(public string $method, public string $path) {}
}
class productcontroller {
#[route('get', '/products')]
public function index() {}
}
#[attribute]
class cache {
public function __construct(public int $duration) {}
}
class productcontroller {
#[cache(3600)]
public function show($id) {}
}
#[attribute]
class throttle {
public function __construct(public int $maxattempts) {}
}
class usercontroller {
#[throttle(5)]
public function store() {}
}
避免对需要多个参数或条件的配置使用属性。以下是不应该做的事情:
#[attribute]
class route {
public function __construct(
public string $method,
public string $path,
public ?string $middleware = null,
public ?string $prefix = null
) {}
}
#[route('post', '/users', middleware: 'auth', prefix: '/admin')]
#[attribute]
class condition {
public function __construct(public string $condition) {}
}
class controller {
#[condition("isadmin() ? 'adminroute' : 'userroute'")]
public function index() {}
}
#[attribute]
class combined {
public function __construct(
public int $cacheduration,
public int $ratelimit
) {}
}
#[combined(cacheduration: 300, ratelimit: 5)]
使用属性作为标记或元数据,而不是在其中嵌入应用程序逻辑。方法如下:
#[attribute]
class required {}
class user {
#[required]
public string $name;
}
#[attribute]
class get {}
class blogcontroller {
#[get]
public function list() {}
}
#[attribute]
class requiresadmin {}
class settingscontroller {
#[requiresadmin]
public function update() {}
}
避免使用属性直接确定应用程序行为。以下是不应该做的事情:
#[attribute]
class accesscontrol {
public function __construct(public string $role) {}
}
#[accesscontrol(role: isadmin() ? 'admin' : 'user')]
#[attribute]
class conditionalcache {
public function __construct(public int $duration) {}
}
#[conditionalcache(duration: userhaspremium() ? 3600 : 300)]
#[attribute]
class cache {
public function __construct(public int $duration) {}
}
#[cache(duration: (int)env('cache_duration'))]
属性非常适合可重用的轻量级注释。以下是一些可重用的注释示例:
#[attribute]
class throttle {
public function __construct(public int $limit) {}
}
#[throttle(5)]
#[attribute]
class cache {
public function __construct(public int $duration) {}
}
#[cache(120)]
#[attribute]
class deprecated {
public function __construct(public string $message) {}
}
#[deprecated("this method will be removed in v2.0")]
某些配置在属性之外可以得到更好的管理。以下是不应该做的事情:
#[attribute]
class middleware {
public function __construct(public string $name) {}
}
#[middleware('auth')]
#[attribute]
class permission {
public function __construct(public string $requiredpermission) {}
}
#[permission("edit_post")]
#[Attribute]
class Validate {
public function __construct(public array $rules) {}
}
#[Validate(['name' => 'required|min:3'])]
属性提供了一种优雅的方式来处理重复配置,特别是在 laravel 这样的 php 框架中。
但是,它们作为简单的元数据效果最好,并且必须避免使用复杂的配置或逻辑使它们过载。
通过遵循最佳实践并将属性用作轻量级、可重用的注释,您可以充分利用它们的潜力,而不会给代码库增加不必要的复杂性。
通过在 github 赞助商上赞助我来支持我的开源工作!您的赞助帮助我不断创建有用的 laravel 软件包、工具和教育内容,让开发者社区受益。感谢您帮助让开源变得更好!
照片由 milad fakurian 在 unsplash 上拍摄
以上就是Working with PHP Attributes: Do’s & Don’ts的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号