项目初始化

数据库

  1. UserName: homestead
  2. Password: secret

数据字典

  • 用户表

  • 商品表 -> 用户

  • 订单表 -> 用户 商品

  • 评价表 -> 用户 商品 订单表

  • 轮播图 ->

  • 分类表 -> 分类表

  • 购物车表 -> 用户 商品

  • 用户地址表 -> 用户

  • 用户收藏表 -> 用户 商品

创建模型

  1. php artisan make:model Address
  2. php artisan make:model Cart
  3. php artisan make:model Category
  4. php artisan make:model City
  5. php artisan make:model Collect
  6. php artisan make:model Comment
  7. php artisan make:model Good
  8. php artisan make:model Order
  9. php artisan make:model OrderDetails
  10. php artisan make:model Slide

购物车模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Cart extends Model
  6. {
  7. use HasFactory;
  8. // 允许批量赋值的字段
  9. protected $fillable = ['user_id', 'goods_id', 'num'];
  10. /**
  11. * 所关联的商品
  12. */
  13. public function goods()
  14. {
  15. return $this->belongsTo(Good::class, 'goods_id', 'id');
  16. }
  17. }

分类模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Category extends Model
  6. {
  7. use HasFactory;
  8. // 可批量赋值的字段
  9. protected $fillable = ['name', 'pid', 'level', 'group'];
  10. /**
  11. * 分类的子类
  12. */
  13. public function children()
  14. {
  15. return $this->hasMany(Category::class, 'pid', 'id');
  16. }
  17. }

城市表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class City extends Model
  6. {
  7. use HasFactory;
  8. // 指定模型关联的表名
  9. protected $table = 'city';
  10. /**
  11. * 子类
  12. */
  13. public function children()
  14. {
  15. return $this->hasMany(City::class, 'pid', 'id');
  16. }
  17. /**
  18. * 父级
  19. */
  20. public function parent()
  21. {
  22. return $this->belongsTo(City::class, 'pid', 'id');
  23. }
  24. }

收藏表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Collect extends Model
  6. {
  7. use HasFactory;
  8. protected $guarded = [];
  9. /**
  10. * 收藏所属于的商品, 一对一
  11. */
  12. public function goods()
  13. {
  14. return $this->belongsTo(Good::class, 'goods_id', 'id');
  15. }
  16. }

评价表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Comment extends Model
  6. {
  7. use HasFactory;
  8. // 不允许批量赋值的字段
  9. protected $guarded = [];
  10. /**
  11. * 强制转换的属性
  12. *
  13. * @var array
  14. */
  15. protected $casts = [
  16. 'pics' => 'array',
  17. ];
  18. /**
  19. * 评论所属用户
  20. */
  21. public function user()
  22. {
  23. return $this->belongsTo(User::class, 'user_id', 'id');
  24. }
  25. /**
  26. * 评论所属商品
  27. */
  28. public function goods()
  29. {
  30. return $this->belongsTo(Good::class, 'goods_id', 'id');
  31. }
  32. }

商品表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Good extends Model
  6. {
  7. use HasFactory;
  8. // 可批量赋值的字段
  9. protected $fillable = [
  10. 'title',
  11. 'user_id',
  12. 'category_id',
  13. 'description',
  14. 'price',
  15. 'stock',
  16. 'cover',
  17. 'pics',
  18. 'is_on',
  19. 'is_recommend',
  20. 'details'
  21. ];
  22. /**
  23. * 强制转换的属性
  24. *
  25. * @var array
  26. */
  27. protected $casts = [
  28. 'pics' => 'array',
  29. ];
  30. /**
  31. * 商品所属的分类
  32. */
  33. public function category()
  34. {
  35. return $this->belongsTo(Category::class, 'category_id', 'id');
  36. }
  37. /**
  38. * 商品所属的用户
  39. */
  40. public function user()
  41. {
  42. return $this->belongsTo(User::class, 'user_id', 'id');
  43. }
  44. /**
  45. * 商品所有的评价
  46. */
  47. public function comments()
  48. {
  49. return $this->hasMany(Comment::class, 'goods_id', 'id');
  50. }
  51. /**
  52. * 商品所有的收藏
  53. */
  54. public function collects()
  55. {
  56. return $this->hasMany(Collect::class, 'goods_id', 'id');
  57. }
  58. }

订单表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Order extends Model
  6. {
  7. use HasFactory;
  8. // 可以批量赋值的字段
  9. protected $fillable = [
  10. 'user_id',
  11. 'order_no',
  12. 'amount',
  13. 'address_id',
  14. 'status',
  15. 'trade_no',
  16. 'pay_type',
  17. 'pay_time'
  18. ];
  19. /**
  20. * 所属用户
  21. */
  22. public function user()
  23. {
  24. return $this->belongsTo(User::class, 'user_id', 'id');
  25. }
  26. /**
  27. * 订单拥有的订单细节
  28. */
  29. public function orderDetails()
  30. {
  31. return $this->hasMany(OrderDetails::class, 'order_id', 'id');
  32. }
  33. /**
  34. * 订单所关联的地址
  35. */
  36. public function orderAddress()
  37. {
  38. return $this->hasOne(Address::class, 'id', 'address_id');
  39. }
  40. /**
  41. * 订单远程一对多, 关联的商品
  42. */
  43. public function goods()
  44. {
  45. return $this->hasManyThrough(
  46. Good::class, // 最终关联的模型
  47. OrderDetails::class, // 中间模型
  48. 'order_id', // 中间模型和本模型关联的外键
  49. 'id', // 最终关联模型的外键
  50. 'id', // 本模型和中间模型关联的键
  51. 'goods_id' // 中间表和最终模型关联的一个键
  52. );
  53. }
  54. }

订单详情表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class OrderDetails extends Model
  6. {
  7. use HasFactory;
  8. // 可批量赋值的字段
  9. protected $fillable = ['order_id', 'goods_id', 'price', 'num'];
  10. /**
  11. * 细节所属订单主表
  12. */
  13. public function order()
  14. {
  15. return $this->belongsTo(Order::class, 'order_id', 'id');
  16. }
  17. /**
  18. * 细节所关系的商品
  19. */
  20. public function goods()
  21. {
  22. return $this->hasOne(Good::class, 'id', 'goods_id');
  23. }
  24. }

轮播图表模型

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Slide extends Model
  6. {
  7. use HasFactory;
  8. protected $fillable = ['title', 'url', 'img', 'status', 'seq'];
  9. }

语言包

文档

  1. composer require laravel-lang/lang:~8.0
复制文件

使用composer(如上所述)将依赖项添加到您的应用程序后,您可以在目录下找到语言文件vendor/laravel-lang/lang

vendor/laravel-lang/lang/src/zh_CN 复制到 resources/lang/zh_CN

config/app.php

  1. 'locale' => 'zh_CN',

时区

config/app.php

  1. 'timezone' => 'Asia/Shanghai',

或者修改为:PRC

Dingo API

安装

  1. composer require dingo/api

Laravel

如果您想在配置文件中进行配置更改,您可以使用以下 Artisan 命令发布它(否则,不需要此步骤):

  1. git init
  2. git status
  3. git add .
  4. git commit -m '初始化项目'
  1. php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

配置相应

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Dingo\Api\Routing\Helpers;
  4. use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
  5. use Illuminate\Foundation\Bus\DispatchesJobs;
  6. use Illuminate\Foundation\Validation\ValidatesRequests;
  7. use Illuminate\Routing\Controller as BaseController;
  8. class Controller extends BaseController
  9. {
  10. use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
  11. use Helpers;
  12. }

配置信息

  1. API_STANDARDS_TREE=x
  2. API_SUBTYPE=shop
  3. API_PREFIX=api
  4. API_VERSION=v1
  5. API_NAME=shop
  6. API_CONDITIONAL_REQUEST=false
  7. API_STRICT=false
  8. API_DEFAULT_FORMAT=json
  9. API_DEBUG=true

创建路由文件

App\Providers\RouteServiceProvider

  1. // 用户认证相关路由
  2. Route::prefix('api')
  3. ->middleware('api')
  4. ->namespace($this->namespace)
  5. ->group(base_path('routes/auth.php'));
  6. // 前台路由
  7. Route::prefix('api')
  8. ->middleware('api')
  9. ->namespace($this->namespace)
  10. ->group(base_path('routes/api.php'));
  11. // 后台路由
  12. Route::prefix('api')
  13. ->middleware('api')
  14. ->namespace($this->namespace)
  15. ->group(base_path('routes/admin.php'));

路由的使用

版本组

为了避免与你主要的项目路由冲突,dingo/api 将会使用其专属的路由实例。要创建端点,我们首先需要获得一个 API 路由的实例:

  1. $api = app('Dingo\Api\Routing\Router');

现在我们必须定义一个版本分组。这种定义方式有利于后续为相同端点新增多版本支持。

  1. $api->version('v1', function ($api) {
  2. });

如果你想一个分组返回多个版本,只需要传递一个版本数组。

  1. $api->version(['v1', 'v2'], function ($api) {
  2. });

通过在第二个参数上传递一个属性数组,你也可以将此组视为特定框架的标准组。

  1. $api->version('v1', ['middleware' => 'foo'], function ($api) {
  2. });

你还可以嵌套常规组以进一步定制某些端点。

  1. $api->version('v1', function ($api) {
  2. $api->group(['middleware' => 'foo'], function ($api) {
  3. });
  4. });

创建路由

一旦你有了一个版本分组,你就可以在分组闭包的参数中,通过 $api 创建端点。

  1. $api->version('v1', function ($api) {
  2. $api->get('users/{id}', 'App\Api\Controllers\UserController@show');
  3. });

创建前台控制器

  1. php artisan make:controller Api/UserController

响应

直接返回模型

  1. class UserController
  2. {
  3. public function show()
  4. {
  5. return User::all();
  6. }
  7. }

你可以返回一个单一的用户。

  1. class UserController
  2. {
  3. public function show($id)
  4. {
  5. return User::findOrFail($id);
  6. }
  7. }

响应生成器

响应生成器提供了一个流畅的接口去方便的建立一个更定制化的响应。响应的生成器通常是与 transformer 相结合。

要利用响应生成器,你的控制器需要使用 Dingo\Api\Routing\Helpers trait。为了在你的控制器里保持引入和使用这个 trait,你可以创建一个基础控制器,然后你的所有的 API 控制器都继承它。

  1. use Dingo\Api\Routing\Helpers;
  2. use Illuminate\Routing\Controller;
  3. class BaseController extends Controller
  4. {
  5. use Helpers;
  6. }

现在你的控制器可以直接继承基础控制器。响应生成器可以在控制器里通过 $response 属性获取。

响应一个数组

  1. class UserController extends BaseController
  2. {
  3. public function show($id)
  4. {
  5. $user = User::findOrFail($id);
  6. return $this->response->array($user->toArray());
  7. }
  8. }

响应一个元素

  1. class UserController extends BaseController
  2. {
  3. public function show($id)
  4. {
  5. $user = User::findOrFail($id);
  6. return $this->response->item($user, new UserTransformer);
  7. }
  8. }

每个Transformer 可以对应一个模型,用来格式化响应的数据。Transformers 创建在APP目录下。Transformers 允许你便捷地、始终如一地将对象转换为一个数组。通过使用一个 transformer 你可以对整数和布尔值,包括分页结果和嵌套关系进行类型转换。

  1. <?php
  2. namespace App\Transformers;
  3. use App\Models\User;
  4. use League\Fractal\TransformerAbstract;
  5. class UserTransformer extends TransformerAbstract
  6. {
  7. public function transform(User $user)
  8. {
  9. return [
  10. 'id' => $user->id,
  11. 'name' => $user->name,
  12. 'email' => $user->email,
  13. 'phone' => $user->phohe,
  14. 'avatar' => $user->avatar,
  15. 'openid' => $user->openid,
  16. ];
  17. }
  18. }

响应一个元素集合

  1. class UserController extends BaseController
  2. {
  3. public function index()
  4. {
  5. $users = User::all();
  6. return $this->response->collection($users, new UserTransformer);
  7. }
  8. }

分页响应

  1. class UserController extends BaseController
  2. {
  3. public function index()
  4. {
  5. $users = User::paginate(25);
  6. return $this->response->paginator($users, new UserTransformer);
  7. }
  8. }

无内容响应

  1. return $this->response->noContent();

创建了资源的响应

  1. return $this->response->created();

错误响应

这有很多不同的方式创建错误响应,你可以快速的生成一个错误响应。

  1. // 一个自定义消息和状态码的普通错误。
  2. return $this->response->error('This is an error.', 404);
  3. // 一个没有找到资源的错误,第一个参数可以传递自定义消息。
  4. return $this->response->errorNotFound();
  5. // 一个 bad request 错误,第一个参数可以传递自定义消息。
  6. return $this->response->errorBadRequest();
  7. // 一个服务器拒绝错误,第一个参数可以传递自定义消息。
  8. return $this->response->errorForbidden();
  9. // 一个内部错误,第一个参数可以传递自定义消息。
  10. return $this->response->errorInternal();
  11. // 一个未认证错误,第一个参数可以传递自定义消息。
  12. return $this->response->errorUnauthorized();

添加 Meta 信息

  1. return $this->response->item($user, new UserTransformer)->addMeta('foo', 'bar');

API 节流

节流限速 (throttling) 允许你限制客户端给定时间的访问次数。限制和过期时间是在限速器里定义的。 默认有两个限速器,验证通过限速器和未验证限速器。

启用节流限制

要为路由或路由组启用节流限制,你必须启用 api.throttle 中间件。 一旦启用了节流限制,你必须已经配置过了一些限制或配置过了具体的路由限制。

在所有的路由中启用节流限制
  1. $api->version('v1', ['middleware' => 'api.throttle'], function ($api) {
  2. // 此版本组中的路由将需要身份认证.
  3. });
路由特定节流

如果只是想限制某些路由或者路由群组,可使用 limitexpires 选项。

  1. $api->version('v1', function ($api) {
  2. $api->get('users', ['middleware' => 'api.throttle', 'limit' => 100, 'expires' => 5, function () {
  3. return User::all();
  4. }]);
  5. });
  1. $api->version('v1', ['middleware' => 'api.throttle', 'limit' => 100, 'expires' => 5], function ($api) {
  2. $api->get('users', function () {
  3. return User::all();
  4. });
  5. $api->get('posts', function () {
  6. return Post::all();
  7. });
  8. });

更多相关文章

  1. 模型关联 响应 中间件 登录 表单验证
  2. laravel 数据库连接、查询构造器和模型
  3. vue 打包后,放到tp5框架中总是报错Uncaught TypeError: Cannot re
  4. laravel 路由
  5. 标准盒模型和弹性盒模型仿PHP中文网导航
  6. 第三课-盒子模型-导航栏
  7. 程序员,你具备这些架构师的能力模型吗
  8. 分析ThinkORM新增加的虚拟模型功能
  9. Python Django模型详解

随机推荐

  1. 美国终于挥舞着霸权大棒向程序员动手了
  2. 【python】使用pip提示ModuleNotFoundErr
  3. JavaScript的前景与未来[每日前端夜话0x9
  4. 回到基础:JavaScript API[每日前端夜话0xA
  5. C语言学习心得(六)
  6. 什么是Deno,它与Node.js有什么不同?[每日前
  7. 成为优秀程序员的101条准则[每日前端夜话
  8. 假装网络工程师28——MPLS跨AS通信option
  9. 如何创建高可用性系统[每日前端夜话0xA2]
  10. Python3版本下创建计算给定日期范围内工