博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
laravel 变量符_使用访问器和变量自动格式化Laravel数据库字段
阅读量:2508 次
发布时间:2019-05-11

本文共 9529 字,大约阅读时间需要 31 分钟。

laravel 变量符

There's a really neat feature in Laravel that often gets overlooked because of the feature's complicated sounding name. We're talking about accessors and mutators.

Laravel中有一个真正整洁的功能,由于其复杂的发音名称,经常会被忽略。 我们正在谈论存取 变异器

What exactly are ?

到底是什么?

  • Accessors: Format something when retrieving from the database

    访问器从数据库检索时设置格式
  • Mutators: Format something when saving to the database

    变异器保存到数据库时格式化某些内容

Both of these can help us save immense amounts of time (and frustration) because we know that whenever retrieving or saving information to our database, we will know it will always be saved in the correct format.

这两种方法都可以帮助我们节省大量的时间(和挫败感),因为我们知道,只要将信息检索或保存到数据库中,我们就会知道信息将始终以正确的格式保存。

One of the most common uses for a mutator is to be sure that a user's password is always hashed before it gets saved into the database. This ensures that you don't have to always remember to hash a password wherever you save a user.

更改器最常见的用途之一是确保在将用户密码保存到数据库之前始终对其进行哈希处理。 这样可确保您不必总是记住在保存用户的任何地方都对哈希进行哈希处理。

基础 (The Basics)

For our examples, let's say that we have a User . These are the fields on our User:

对于我们的示例,假设我们有一个User 。 这些是我们用户的字段:

- first_name- last_name- email- username- password- expires_at- explodes_at- gets_mad_at

For our most basic of examples, let's say that we always want to ensure that when we grab a user, their first name is capitalized. This is so we can display it to our users and not have to worry about all lowercase names.

对于我们最基本的示例,假设我们总是要确保在抓住用户时,其名字大写。 这样我们就可以将其显示给我们的用户,而不必担心所有小写的名称。

Here is the code for when we create a user:

这是创建用户时的代码:

$user = App\User::create([    'first_name'  => 'chris',    'last_name'   => 'sevilleja',    'email'       => 'chris&64;scotch.io',    'password'    => 'password',    'expires_at'  => Carbon::now()->addMonth(),    'explodes_at' => Carbon::now()->addDay(),    'gets_mad_at' => Carbon::yesterday()]);

Our user didn't care to enter in their first name or last name with the proper punctuation but we still want to show their name as capitalized. If we save our user to the database with the above, we'll need to use an accessor to format the user's first_name and last_name when we retrieve them.

我们的用户不希望使用正确的标点符号输入他们的名字或姓氏,但我们仍然希望将其名字显示为大写。 如果使用上述方法将用户保存到数据库中,则在检索用户时,需要使用访问器来格式化用户的first_namelast_name

访问器使用getAttribute (Accessors use getAttribute)

An accessor will be defined on our User model:

访问器将在我们的User模型上定义:

Very easy to do. We just define a getAttribute() method and make sure that we camel case the attribute name (first_name turns into getFirstName).

很容易做到。 我们只定义一个getAttribute()方法,并确保我们驼峰化属性名称( first_name变成getFirstName )。

Then we use PHP's function to capitalize the first letter. Easy!

然后,我们使用PHP的函数将首字母大写。 简单!

变异者使用setAttribute (Mutators use setAttribute)

Now let's say we wanted to handle capitalizing a user's name when we save them to the database so that our database is uniform in all of its name fields. Just like how we created the getAttribute method, we'll create a setAttribute method.

现在假设我们要在将用户名保存到数据库时处理大写形式,以便我们的数据库在其所有名称字段中都是统一的。 就像我们创建getAttribute方法一样,我们将创建一个setAttribute方法。

The process itself will be a little different though.

该过程本身将有所不同。

attributes['first_name'] = ucfirst($value); } /** * Always capitalize the last name when we save it to the database */ public function setLastNameAttribute($value) { $this->attributes['last_name'] = ucfirst($value); }}

The big difference is we are adding Attribute to the naming convention here and instead of returning something (we're not getting anything), we'll directly call the attribute on the model using $this->attributes.

最大的不同是,我们在此处将Attribute添加到命名约定中,而不是返回任何内容(我们没有得到任何东西),我们将使用$this->attributes直接在模型上调用该$this->attributes

Now whenever we save to the database, we can make sure that these fields are capitalized.

现在,无论何时保存到数据库,我们都可以确保将这些字段大写。

我用哪一个? (Which do I use?)

Now that we've seen accessors and mutators in action, which do you use and when? That really all depends on the scenario. Sometimes you'll need to only use an accessor or mutator; other times you will need to use both.

现在,我们已经看到访问器和更改器在起作用,您在何时使用哪个? 这真的取决于场景。 有时,您只需要使用访问器或更改器即可; 其他时候,您将需要同时使用两者。

An instance of just using a mutator would be hashing passwords. We're not going to unhash a password when we retrieve it.

仅使用增幅器的实例就是哈希密码。 检索密码时,我们不会取消散列密码。

A time we would use both accessor and mutator is for json_encodeing and json_decodeing JSON objects in a Postgres database.

我们将访问器和json_decode器同时使用的时间是Postgres数据库中的json_encodejson_decode JSON对象。

Let's look at some more examples to get the hang of things.

让我们看一些更多的例子来掌握一切。

散列密码 (Hashing Passwords)

Here's a really quick example of how we can always ensure that passwords are never saved plain text into our database.

这是一个非常简单的示例,说明了如何始终确保密码永远不会以纯文本格式保存到我们的数据库中。

attributes['password'] = Hash::make($value); }}

编码和解码JSON对象 (Encoding and Decoding JSON Objects)

Let's say we add a field to our User model called settings and we store all their settings in a JSON field.

假设我们向User模型添加了一个名为settings的字段,并将所有设置存储在JSON字段中。

// get the scotchyscotch user$user = App\User::where('username', 'scotchyscotch')->first();// give them some settings$user->settings = [    'notifications' => true,    'location'      => 'Las Vegas'];

Now this wouldn't save to our database since it's an array going into a JSON field. We could json_encode the settings field but that would be tedious to remember to do it all over our application.

现在这不会保存到我们的数据库中,因为它是进入JSON字段的数组。 我们可以对settings字段进行json_encode ,但是要记住在整个应用程序中都要做这很json_encode

We would also have to remember to json_decode this settings field whenever we grabbbed a user.

我们还必须记住json_decodesettings ,每当我们grabbbed用户领域。

Luckily we can use an accessor and a mutator to ensure this settings field is always the way we want it to be.

幸运的是,我们可以使用访问器和更改器来确保此settings字段始终是我们想要的方式。

attributes['settings'] = json_encode($value); }}

弹头Sl (Slug-ifying Slugs)

Another quick example is when we are saving an article to a database. We will need to have a slug for that article.

另一个快速的例子是当我们将文章保存到数据库中时。 我们需要有一个slug了那篇文章。

// the article$title = 'What Does Water on Mars Mean?';// the slug$slug = 'what-does-water-on-mars-mean';

We wouldn't want to have to have a user enter in the slug every time they saved a new article. We can use a mutator to create the slug for us!

我们不需要每次保存新文章时都让用户输入该条目。 我们可以使用变子为我们创建弹头!

attributes['slug'] = str_slug($this->title); }}

We are calling $this->title and the Laravel helper method to create the slug attribute when we save our model.

保存模型时,我们调用$this->title和Laravel帮助器方法来创建slug属性。

We are using $this->title instead of $this->attributes['title'] because we are not actually setting the title, we just want to get it.

我们使用的是$this->title而不是$this->attributes['title']因为我们实际上并未设置标题,我们只是想获取它。

始终获取日期对象 (Always Get Date Objects)

It is much easier to use , the extension of the native PHP DateTime class when dealing with dates or times.

使用 (本机PHP DateTime类的扩展)处理日期或时间要容易得多。

// this is much easier$date = Carbon::now();$date = $date->addMonth();// than dealing with this$date = '2012-01-31 00:00:00';$date = date('Y-m-d', strtotime('+1 month', $date));

The DateTime string is not the easiest thing to read or work with so we usually have to use Carbon to work with our dates. Laravel handily makes sure that all of our dates are stored in the correct format.

DateTime字符串不是最容易阅读或使用的东西,因此我们通常必须使用Carbon来处理日期。 Laravel会确保我们所有的日期都以正确的格式存储。

When saving our dates, we are allowed to pass in different dates like so:

保存日期时,我们可以像这样传递不同的日期:

// get the awesomedude user$user = App\User::where('username', 'awesomedude')->first();// all are valid ways to set the date$user->expires_at = '2015-09-30 23:01:34';$user->expires_at = '2015-06-26';$user->expires_at = Carbon::now();$user->expires_at = Carbon::tomorrow();$user->expires_at = 1443765240; // unix timestamp// save the user$user->save();

How does Laravel know which fields are dates though? That can be defined on the Eloquent Model using the $dates property. By default, the created_at and updated_at fields are automatically mutated into dates.

Laravel如何知道日期是哪些字段? 可以使用$dates属性在Eloquent模型上定义。 默认情况下, created_atupdated_at字段会自动突变为日期。

Unlike the above accessors/mutators where we define a specific method, we can override the default dates and set more date fields to be mutated by overriding the $dates property on our model like so:

与上面定义了特定方法的访问器/更改器不同,我们可以覆盖默认日期,并通过覆盖模型上的$dates属性来设置更多要更改的日期字段,如下所示:

All of the fields above will be set to the proper date type now when saving our model.

保存模型时,以上所有字段现在都将设置为正确的日期类型。

Inversely, all of the $dates fields will be casted into Carbon instances upon retrieval.

相反,所有$dates字段将在检索时强制转换为Carbon实例。

// get awesomedudette$user = App\User::where('username', 'awesomedudette')->first();// find an hour before the time this user explodes at$explodeWarning = $user->explodes_at->subHour();

结论 (Conclusion)

When working with a large application and large teams of developers, it's always a good idea to have safety valves in precise places so simple errors don't slip through the cracks.

当与大型应用程序和大型开发人员团队合作时,将安全阀放置在精确的位置总是一个好主意,这样简单的错误就不会越过裂缝。

With accessors and mutators, your entire application will always take certain actions when dealing with the database. No plain text passwords, never having to remember to json_decode a field, and having easy to use dates at all times are great reasons to use another useful Laravel feature.

使用访问器和更改器,您的整个应用程序在处理数据库时将始终执行某些操作。 没有纯文本密码,不必记住要对字段进行json_decode ,并且json_decode具有易于使用的日期是使用其他有用的Laravel功能的重要原因。

翻译自:

laravel 变量符

转载地址:http://xnywd.baihongyu.com/

你可能感兴趣的文章
redux、immutablejs和mobx性能对比(三)
查看>>
jQuery实现简单而且很酷的返回顶部链接效果
查看>>
mac 终端 常用命令
查看>>
EGL接口介绍-----Android OpenGL ES底层开发
查看>>
电梯调度程序的UI设计
查看>>
转自 zera php中extends和implements的区别
查看>>
Array.of使用实例
查看>>
【Luogu】P2498拯救小云公主(spfa)
查看>>
如何获取网站icon
查看>>
几种排序写法
查看>>
java 多线程的应用场景
查看>>
dell support
查看>>
转:Maven项目编译后classes文件中没有dao的xml文件以及没有resources中的配置文件的问题解决...
查看>>
解决“Eclipse中启动Tomcat后,http://localhost:8080/无法访问”的问题
查看>>
LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
查看>>
百度杯WriteUp
查看>>
test
查看>>
系统日志2-日志查询
查看>>
作用域和 DOM
查看>>
P1280 尼克的任务
查看>>