Laravel在哪里放置/如何处理枚举? [英] Where to put/how to handle enums in Laravel?
问题描述
Laravel具有一个<select>
表单帮助器,该输入器将字典作为输入.我喜欢将所有这些价值观保持在中心位置.例如,我可能有一个如下所示的枚举:
Laravel has a <select>
form helper which takes as input a dictionary. I like to keep the values for all of these in a central place. For example, I might have an enum that looks like this:
$phoneTypes = [
'CELL' => "Cellular",
'HOME' => "Home",
'WORK' => "Work",
];
我想同时在视图/模板和数据库中使用
Which I want to use in both my view/template, and in the database:
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->enum('pri_phone_type',array_keys($phoneTypes));
...
});
- 有推荐的放置这些的地方吗?
- 我可以将它们设置为全局,以便我可以在所有视图中轻松访问它们吗?
推荐答案
您有几种处理枚举的选项.在开始讨论之前,我强烈建议您不要使用DB enum
列类型.
You have several options for handling enums. Before we look at a few though, I would first strongly encourage you not to use the DB enum
column type.
数据库枚举由于许多原因而有问题.我建议例如阅读这篇文章:
Database enums are problematic for a number of reasons. I suggest reading this article for example:
http://komlenic.com /244/8-reasons-why-mysqls-enum-data-type-is-evil/
因此,让我们看看其他一些选择.
So with that let's look at a few other options.
由于您使用的是Laravel,一个非常简单的选项是将一系列选项粘贴在配置文件中.
Since you're using Laravel, one very simple option is to stick an array of options in a config file.
假设您使用以下内容创建新文件config/enums.php
:
Say you create a new file config/enums.php
with the following:
return [
'phone_types' => [
'CELL' => "Cellular",
'HOME' => "Home",
'WORK' => "Work",
]
];
您现在可以在代码中的任何位置访问config('enums.phone_types')
,包括Blade模板.
You can now access config('enums.phone_types')
anywhere in your code, including your Blade template.
@Banford的答案显示了如何使用类常量进行基本的枚举类型的行为.如果您喜欢这种方法,建议您阅读这篇基于此概念的文章和程序包,以提供强类型的枚举:
@Banford's answer shows how to do basic enum-type behavior with class constants. If you like that approach, I recommend looking at this article and package which builds on this concept to provide strongly type enums:
https://stitcher.io/blog/php-enums
https://github.com/spatie/enum
您将创建一个这样的类:
You would create a class like this:
/**
* @method static self cell()
* @method static self home()
* @method static self work()
*/
class PhoneTypes extends Enum
{
}
现在您可以在应用程序中调用PhoneTypes::home()
.如果需要,请查看该软件包的文档,以了解如何创建值映射.
And now you can call PhoneTypes::home()
in your app. Check out the documentation for that package to see how you can create a map of values, if you want.
如果您真的要管理数据库中的选项,我将创建一个单独的phone_types
数据库表,并与您的customers
表建立关系.与使用enum
列类型相比,这是 still 更好的选择.
If you really want to manage your options in the database, I'd create a separate phone_types
database table and create a relationship with your customers
table. This is still a much better option than using enum
column type.
这篇关于Laravel在哪里放置/如何处理枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!