Explorar el Código

构建商品服务接口(五):客户端代码重构

chenlong hace 4 años
padre
commit
9f4b2aa28d
Se han modificado 3 ficheros con 276 adiciones y 0 borrados
  1. 112 0
      app/MicroApi/Items/ProductItem.php
  2. 146 0
      app/MicroApi/Services/ProductService.php
  3. 18 0
      routes/api.php

+ 112 - 0
app/MicroApi/Items/ProductItem.php

@@ -0,0 +1,112 @@
+<?php
+namespace App\MicroApi\Items;
+
+class ProductItem
+{
+    public $id;
+    public $brand_id;
+    public $sku;
+    public $name;
+    public $slug;
+    public $status;
+    public $description;
+    public $cover;
+    public $quantity;
+    public $price;
+    public $sale_price;
+    public $length;
+    public $width;
+    public $height;
+    public $weight;
+    public $distance_unit;
+    public $mass_unit;
+    public $created_at;
+    public $updated_at;
+    public $brand;
+    public $categories;
+    public $images;
+    public $attributes;
+
+    public function fillAttributes($data)
+    {
+        if (is_object($data)) {
+            $data = get_object_vars($data);
+        }
+        foreach ($data as $key => $value) {
+            switch (strtolower($key)) {
+                case 'id':
+                    $this->id = $value;
+                    break;
+                case 'brand_id':
+                    $this->brand_id = $value;
+                    break;
+                case 'sku':
+                    $this->sku = $value;
+                    break;
+                case 'name':
+                    $this->name = $value;
+                    break;
+                case 'slug':
+                    $this->slug = $value;
+                    break;
+                case 'status':
+                    $this->status = $value;
+                    break;
+                case 'description':
+                    $this->description = $value;
+                    break;
+                case 'cover':
+                    $this->cover = $value;
+                    break;
+                case 'quantity':
+                    $this->quantity = $value;
+                    break;
+                case 'price':
+                    $this->price = $value;
+                    break;
+                case 'sale_price':
+                    $this->sale_price = $value;
+                    break;
+                case 'length':
+                    $this->length = $value;
+                    break;
+                case 'width':
+                    $this->width = $value;
+                    break;
+                case 'height':
+                    $this->height = $value;
+                    break;
+                case 'weight':
+                    $this->weight = $value;
+                    break;
+                case 'distance_unit':
+                    $this->distance_unit = $value;
+                    break;
+                case 'mass_unit':
+                    $this->mass_unit = $value;
+                    break;
+                case 'created_at':
+                    $this->created_at = $value;
+                    break;
+                case 'updated_at':
+                    $this->updated_at = $value;
+                    break;
+                case 'brand':
+                    $this->brand = $value;
+                    break;
+                case 'images':
+                    $this->images = $value;
+                    break;
+                case 'categories':
+                    $this->categories = $value;
+                    break;
+                case 'attributes':
+                    $this->attributes = $value;
+                    break;
+                default:
+                    break;
+            }
+        }
+        return $this;
+    }
+}

+ 146 - 0
app/MicroApi/Services/ProductService.php

@@ -0,0 +1,146 @@
+<?php
+namespace App\MicroApi\Services;
+
+use App\MicroApi\Exceptions\RpcException;
+use App\MicroApi\Facades\HttpClient;
+use App\MicroApi\Items\ProductItem;
+use Illuminate\Support\Facades\Log;
+
+class ProductService
+{
+    use DataHandler;
+
+    protected $servicePrefix = '/product/productService';
+
+    /**
+     * @param $product
+     * @return ProductItem
+     * @throws RpcException
+     */
+    public function create(ProductItem $product)
+    {
+        $path = $this->servicePrefix . '/create';
+        $options = ['json' => $product];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.Create Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return isset($result->product) ? $product->fillAttributes($result->product) : null;
+    }
+
+    /**
+     * 获取商品集合
+     * @return \Illuminate\Support\Collection|null
+     * @throws RpcException
+     */
+    public function getAll()
+    {
+        $path = $this->servicePrefix . '/getAll';
+        try {
+            $response = HttpClient::get($path);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.GetAll Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        // 返回商品集合
+        return isset($result->products) ? collect($result->products)->map(function ($item) {
+            $product = new ProductItem();
+            return $product->fillAttributes($item);
+        })->reject(function ($item){
+            return empty($item);
+        }) : null;
+    }
+
+    /**
+     * 根据商品 ID 获取商品信息
+     * @param $id
+     * @param $withRelations
+     * @return ProductItem|null
+     * @throws RpcException
+     */
+    public function getById($id, $withRelations = false)
+    {
+        if ($withRelations == false) {
+            $path = $this->servicePrefix . '/get';
+        } else {
+            $path = $this->servicePrefix . '/getDetail';
+        }
+        $product = new ProductItem();
+        $product->id = $id;
+        $options = ['json' => $product];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.Get Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return isset($result->product) ? $product->fillAttributes($result->product) : null;
+    }
+
+    /**
+     * 通过商品别名获取明细
+     * @param $slug
+     * @return ProductItem|null
+     * @throws RpcException
+     */
+    public function getBySlug($slug)
+    {
+        $path = $this->servicePrefix . '/get';
+        $product = new ProductItem();
+        $product->slug = $slug;
+        $options = ['json' => $product];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.Get Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return isset($result->user) ? $product->fillAttributes($product) : null;
+    }
+
+    /**
+     * 更新商品信息
+     * @param ProductItem $product
+     * @return ProductItem
+     * @throws RpcException
+     */
+    public function update(ProductItem $product)
+    {
+        $path = $this->servicePrefix . '/update';
+        $options = ['json' => $product];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.Update Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return $product->fillAttributes($result->product);
+    }
+
+    /**
+     * 删除商品信息
+     * @param $productId
+     * @return bool
+     * @throws RpcException
+     */
+    public function delete($productId)
+    {
+        $path = $this->servicePrefix . '/delete';
+        $options = ['json' => ['id' => $productId]];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.ProductService.Delete Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return empty($result->product) ? true : false;
+    }
+}

+ 18 - 0
routes/api.php

@@ -17,3 +17,21 @@ use Illuminate\Support\Facades\Route;
 Route::middleware('auth:api')->get('/user', function (Request $request) {
     return $request->user();
 });
+
+Route::get('/product/test', function (Request $request) {
+    $productService = new \App\MicroApi\Services\ProductService();
+
+    $product = new \App\MicroApi\Items\ProductItem();
+    $product->brand_id = 1;
+    $product->sku = \Illuminate\Support\Str::random(16);
+    $product->name = "微服务架构";
+    $product->slug = 'microservice';
+    $product->description = "基于 Laravel + Go Micro 框架构建微服务系统";
+    $product->cover = 'https://qcdn.xueyuanjun.com/wp-content/uploads/2019/06/94fe5973d09b0ad753082b6b1ba46f3d.jpeg';
+    $product->price = 199;
+    $product->sale_price = 99;
+    $product->quantity = 1000;
+    $newProduct = $productService->create($product);
+
+    dd($productService->getById($newProduct->id, true));
+});