感觉好长时间没写东西了,一方面主要是自己的角色发生了变化,每天要面对各种各样的事情和突发事件,不能再有一个完整的长时间让自己静下来写代码,或者写文章。

另一方面现在公司技术栈不再停留在只有 Laravel + VUE 了,我们还有小程序、APP 等开发,所以我关注的东西也就多了。

接下来我还是会继续持续「高产」,把写技术文章当作一个习惯,坚持下去。

好了,废话不多说,今天来说一说「Eloquent: 修改器」。

一直想好好研究下 Eloquent。但苦于 Eloquent 有太多可研究的,无法找到一个切入点。前两天看一同事好像对这个「Eloquent: 修改器」了解不多,所以今天就拿它作为入口,扒一扒其实现源代码。

首先还是拿一个 Demo 为例:

Demo

<?php
namespace App\Models;use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;class Baby extends Model
{protected $table = 'baby';protected $appends = ['age'];public function getAgeAttribute(){$date = new Carbon($this->birthday);return Carbon::now()->diffInYears($date);}
}

这个代码比较简单,就是通过已有属性 birthday,计算 Baby 几岁了,得到 age 属性。

前端就可以直接拿到结果:

return $baby->age;

同样的,还有 setXxxAttribute 方法来定义一个修改器。

源代码

读代码还是从使用入手,如上通过 $baby->age 调用 age 属性,这个属性没在类中定义,所以只能通过 PHP 的魔术方法 __get() 调用了。

我们看看 Model 类的 __get() 方法:

/*** Dynamically retrieve attributes on the model.** @param  string  $key* @return mixed*/
public function __get($key)
{return $this->getAttribute($key);
}

好了,我们开始解读源代码了:

/*** Get an attribute from the model.** @param  string  $key* @return mixed*/
public function getAttribute($key)
{if (! $key) {return;}// If the attribute exists in the attribute array or has a "get" mutator we will// get the attribute's value. Otherwise, we will proceed as if the developers// are asking for a relationship's value. This covers both types of values.if (array_key_exists($key, $this->attributes) ||$this->hasGetMutator($key)) {return $this->getAttributeValue($key);}...
}

重点自然就在第二个 if 上,主要判断 attributes 数组中是否包含该属性,如果没有,则会执行函数 $this->hasGetMutator($key)

/*** Determine if a get mutator exists for an attribute.** @param  string  $key* @return bool*/
public function hasGetMutator($key)
{return method_exists($this, 'get'.Str::studly($key).'Attribute');
}

这就对上了我们的 Demo 中自定义的函数 getAgeAttribute(),也就返回 true 了。

接下来就是执行函数 $this->getAttributeValue($key),进而执行函数:return $this->mutateAttribute($key, $value);

/*** Get the value of an attribute using its mutator.** @param  string  $key* @param  mixed  $value* @return mixed*/
protected function mutateAttribute($key, $value)
{return $this->{'get'.Str::studly($key).'Attribute'}($value);
}

好了,到此我们基本就知道了获取自定义 Attribute 的流程了。

相信解析 set XxxAttribute 也是很简单的。

总结

好长时间没写东西了,先从最简单的入手,练练手。解析 Eloquent 需要费很多脑细胞,接下来的一段时间我会围绕着这个主题好好研究下去,尽可能的全部解读一遍::

.
|____Capsule
| |____Manager.php
|____composer.json
|____Concerns
| |____BuildsQueries.php
| |____ManagesTransactions.php
|____Connection.php
|____ConnectionInterface.php
|____ConnectionResolver.php
|____ConnectionResolverInterface.php
|____Connectors
| |____ConnectionFactory.php
| |____Connector.php
| |____ConnectorInterface.php
| |____MySqlConnector.php
| |____PostgresConnector.php
| |____SQLiteConnector.php
| |____SqlServerConnector.php
|____Console
| |____Factories
| | |____FactoryMakeCommand.php
| | |____stubs
| | | |____factory.stub
| |____Migrations
| | |____BaseCommand.php
| | |____FreshCommand.php
| | |____InstallCommand.php
| | |____MigrateCommand.php
| | |____MigrateMakeCommand.php
| | |____RefreshCommand.php
| | |____ResetCommand.php
| | |____RollbackCommand.php
| | |____StatusCommand.php
| |____Seeds
| | |____SeedCommand.php
| | |____SeederMakeCommand.php
| | |____stubs
| | | |____seeder.stub
|____DatabaseManager.php
|____DatabaseServiceProvider.php
|____DetectsDeadlocks.php
|____DetectsLostConnections.php
|____Eloquent
| |____Builder.php
| |____Collection.php
| |____Concerns
| | |____GuardsAttributes.php
| | |____HasAttributes.php
| | |____HasEvents.php
| | |____HasGlobalScopes.php
| | |____HasRelationships.php
| | |____HasTimestamps.php
| | |____HidesAttributes.php
| | |____QueriesRelationships.php
| |____Factory.php
| |____FactoryBuilder.php
| |____JsonEncodingException.php
| |____MassAssignmentException.php
| |____Model.php
| |____ModelNotFoundException.php
| |____QueueEntityResolver.php
| |____RelationNotFoundException.php
| |____Relations
| | |____BelongsTo.php
| | |____BelongsToMany.php
| | |____Concerns
| | | |____InteractsWithPivotTable.php
| | | |____SupportsDefaultModels.php
| | |____HasMany.php
| | |____HasManyThrough.php
| | |____HasOne.php
| | |____HasOneOrMany.php
| | |____MorphMany.php
| | |____MorphOne.php
| | |____MorphOneOrMany.php
| | |____MorphPivot.php
| | |____MorphTo.php
| | |____MorphToMany.php
| | |____Pivot.php
| | |____Relation.php
| |____Scope.php
| |____SoftDeletes.php
| |____SoftDeletingScope.php
|____Events
| |____ConnectionEvent.php
| |____QueryExecuted.php
| |____StatementPrepared.php
| |____TransactionBeginning.php
| |____TransactionCommitted.php
| |____TransactionRolledBack.php
|____Grammar.php
|____Migrations
| |____DatabaseMigrationRepository.php
| |____Migration.php
| |____MigrationCreator.php
| |____MigrationRepositoryInterface.php
| |____Migrator.php
| |____stubs
| | |____blank.stub
| | |____create.stub
| | |____update.stub
|____MigrationServiceProvider.php
|____MySqlConnection.php
|____PostgresConnection.php
|____Query
| |____Builder.php
| |____Expression.php
| |____Grammars
| | |____Grammar.php
| | |____MySqlGrammar.php
| | |____PostgresGrammar.php
| | |____SQLiteGrammar.php
| | |____SqlServerGrammar.php
| |____JoinClause.php
| |____JsonExpression.php
| |____Processors
| | |____MySqlProcessor.php
| | |____PostgresProcessor.php
| | |____Processor.php
| | |____SQLiteProcessor.php
| | |____SqlServerProcessor.php
|____QueryException.php
|____README.md
|____Schema
| |____Blueprint.php
| |____Builder.php
| |____Grammars
| | |____ChangeColumn.php
| | |____Grammar.php
| | |____MySqlGrammar.php
| | |____PostgresGrammar.php
| | |____RenameColumn.php
| | |____SQLiteGrammar.php
| | |____SqlServerGrammar.php
| |____MySqlBuilder.php
| |____PostgresBuilder.php
| |____SQLiteBuilder.php
| |____SqlServerBuilder.php
|____Seeder.php

参考

  • Eloquent: 修改器 https://laravel-china.org/docs/laravel/5.7/eloquent-mutators/2297
  • __get()使用说明 http://php.net/manual/zh/language.oop5.overloading.php#object.get

未完待续

Eloquent: 修改器相关推荐

  1. Laravel学习记录--访问器与修改器

    简介 当你在Eloquent模型实例中获取或设置某些属性值的时候,访问器和修改器允许你对Eloquent属性值进行格式化,访问器可在将要读取的数据进行处理后在返回给调用方,而修改器可在数据要被保存到数 ...

  2. laravel获取器和修改器

    laravel获取器和修改器 获取器 修改器 获取器 Eloquent 提供了一种便利的方法,可以在获取或设定属性时进行转换.要定义获取器,只要在模型里加入类似 getXxxxAttribute 的方 ...

  3. MongoDB update修改器: 针对Fields的$修改器 $inc $set $unset

    MongoDB update修改器: $inc $set $unset $push $pull $pop 针对Fields的$修改器 $set: { $set: { key: value } } $s ...

  4. MongoDB修改器的使用1

    为什么要使用修改器?     通常我们只会修改文档的一部分,这时候更新整个文档就显得很麻烦,通常是通过原子性的更新修改器来完成. 1."$set"修改器    "$set ...

  5. thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法)

    thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法) 一.总结 记得看下面 1.获取器的作用是在获取数据的字段值后自动进行处理 2.修改器的作用是可以在数据赋值的时候自动进行转换处 ...

  6. 【v2.x OGE-example 第二章(第二节) 修改器的使用】

    2019独角兽企业重金招聘Python工程师标准>>> [v2.x OGE-example 第二章(第二节) 修改器的使用] 1. 位置:Modifier_example --> ...

  7. 利用cheat engine以及VC编写游戏修改器

    cheat engine的介绍已经完毕了,下面就是怎么使用它的问题,这里写一个稍微有意思一点的,也有实际用途的话题,就是来编写自己的游戏修改器. 这篇文章参考了http://www.pediy.com ...

  8. IP修改器的作用以及用途

    现在网络无处不在,有一些网站会对用户有一定的限制,比如不能频繁发帖,不能一直频繁访问,那么遇到这些问题怎能办呢? 每一台连接了互联网的电脑都有一个唯一的IP地址如同我们每一个人的×××号码一样,那么这 ...

  9. mongodb 学习笔记 2 --- 修改器

    修改器是为了爱update文档时,不需要传入整个文档就能修改当前文档的某个属性值,修改器用法如下: 假设数据库中foo集合中存在如下文档:{"name":"jack&qu ...

  10. MongoDB(课时18 修改器)

    3.4.3.2 修改器(原子操作) 对MongoDB数据库而言,数据的修改会牵扯到内容的变更,结构的变更(包含数组),所以在MongoDB在设计的时候就提供有一系列的修改器的应用,那么像之前使用的&q ...

最新文章

  1. HotSpot 自动内存管理笔记与实战
  2. 分别写出引入CSS的3种方式, 特点, 优先级
  3. html5 拍照 清晰度,html5强大的功能(一)
  4. Java ClassLoader getSystemClassLoader()方法与示例
  5. 你真的适合做前端吗?自学入行的那些坑
  6. Spring Boot 快速集成第三方登录功能
  7. 控制抽象之简化客户代码
  8. 第十六章 复杂的抽像类结构
  9. tcp/ip协议初识
  10. linux内核之字符设备驱动图解
  11. Cisco PIX 简单配置-4
  12. 秩和比(RSR)指标计算
  13. Win10,Office2016及以上图标异常解决方案
  14. 《数据库系统原理》 课程代码: 04735 - 第三章 数据库设计 - 第一节 数据库设计概述
  15. 云盘服务器被毁,360云盘宣布停止个人云盘服务 明年2月1日清空
  16. 红警conquer.mix文件
  17. 有了天猫精灵智能套组,享受管家级别智能服务
  18. python inplace
  19. python五种基本数据类型_五大Python基础数据类型
  20. 再谈 RocketMQ broker busy(实战篇)

热门文章

  1. 【12c】新特性:Oracle 12c Temporal Validity 时间有效性
  2. JSHOP2环境配置
  3. python3 练习题100道,孰能生巧,之前要想一个下午的内容,马上就有了答案
  4. 【软件工程】决策表和决策树
  5. Php维语翻译,维语翻译_维吾尔翻译_维语翻译在线
  6. bat批处理文件夹内文件名的提取
  7. java数组 处理函数 chunk_数组分组chunk的一种写法
  8. python使用matplotlib绘制3D图
  9. 北大oj百练-1003
  10. flutter 返回键监听