
Builder.php
<?phpnamespace App\Extensions;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Log;use Symfony\Component\HttpKernel\Exception\HttpException;use Illuminate\Database\Eloquent\Builder as EloquentBuilder;use Illuminate\Database\Query\Builder as QueryBuilder;use Throwable;/*** @property-read Model $model* @property-read EloquentBuilder|null $query* @property-read string|null $table* @property-read QueryBuilder|null $rawQuery*/class Builder{private ?string $modelClass = null;private ?string $table = null;public function __get(string $name){switch ($name) {case 'table':if (!$this->table) {$this->table = $this->makeModel()->getTable();}return $this->table;case 'model':return $this->makeModel();case 'query':return $this->makeModel(false)::query();case 'rawQuery':abort_if($this->table === null,'获取当前模型错误',403);return DB::table($this->table);default:return null;}}private function getModel(): string{if (!$this->modelClass) {$baseName = last(explode('\\', get_called_class()));if (str_ends_with($baseName, 'Service')) {$baseName = substr($baseName, 0, -7);} else if (str_ends_with($baseName, 'Repository')) {$baseName = substr($baseName, 0, -10);}$class = 'App\\Models\\' . $baseName;if (!class_exists($class)) {abort(500,'缺少模型');}$this->modelClass = $class;return $this->modelClass;}return $this->modelClass;}private function makeModel($instance = true): Model|string{$class = $this->getModel();if (!is_subclass_of($class, Model::class)) {Log::error('模型文件错误');abort(500,'模型文件错误');}if (!$instance) {return $class;}try {return app($class);} catch (Throwable $e) {throw new HttpException(500, $e->getMessage());}}}
BaseService.php
实现了增、删、改
<?php
namespace App\Services;
use App\Extensions\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
class BaseService extends Builder
{
public function createOrUpdate(array $data, string $by = 'id'): Model|EloquentBuilder|null
{
if ($byVal = ($data[$by] ?? null)) {
if ($by === 'id') {
unset($data['id']);
}
return $this->query->updateOrCreate([$by => $byVal], $data);
}
return $this->query->create($data);
}
public function destroy(int $value, string $by = 'id')
{
if (blank($value)) {
abort(422,'参数不能为空');
}
$m = $this->query->where($by, $value)->first();
try {
$m->delete();
} catch (ModelNotFoundException) {
abort(422,'数据不存在');
} catch (\Exception $e) {
Log::error('[' . class_basename($this) . '::destroy' . $e->getMessage());
abort(500,'删除数据失败!');
}
}
}
BaseRepository.php
<?php
namespace App\Repository;
use App\Extensions\Builder;
abstract class BaseRepository extends Builder
{
}
