Chapter 05

処理スクラップ

ta.toshio
ta.toshio
2021.04.22に更新

独自モジュール読み込み

https://github.com/avored/framework/blob/master/src/Modules/Manager.php

独自に用意したフォルダ内にregister.ymlが存在すれば、用意したモジュールをサービスプロバイダとして登録する。

    /**
     * Scan Module Path and load into a moduleList Collection.
     * @return self $this
     */
    protected function loadModules()
    {
        $modulePath = base_path('modules');

        if (File::exists($modulePath)) {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($modulePath, RecursiveDirectoryIterator::FOLLOW_SYMLINKS)
            );

            $iterator->setMaxDepth(2);
            $iterator->rewind();

            while ($iterator->valid()) {
                if (($iterator->getDepth() > 1) &&
                    $iterator->isFile() &&
                    ($iterator->getFilename() == 'register.yml')) {
                    $filePath = $iterator->getPathname();
                    $moduleRegisterContent = File::get($filePath);
                    $data = Yaml::parse($moduleRegisterContent);

                    $module = new Module();
                    $module->namespace($data['namespace']);
                    $module->identifier($data['identifier']);
                    $module->name($data['name']);
                    $module->status($data['status']);
                    $module->description($data['description']);
                    $module->basePath($iterator->getPath());
                    $module->publishedTags($data['published_tags'] ?? []);

                    // read and store dependency declaration
                    $dependencies = empty($data['dependencies']) ? [] : explode(',', str_replace(' ', '', $data['dependencies']));
                    $module->dependencies($dependencies);

                    $this->moduleList->put($module->identifier(), $module);
                }
                $iterator->next();
            }
            // Sort modules based on its declared dependency
            $this->moduleList = $this->sortByDependency($this->moduleList);
            
            $this->moduleList->each(function ($module) {
                $composerLoader = require base_path('vendor/autoload.php');
                if (strtolower($module->status()) == 'active') {
                    $path = $module->basePath() . DIRECTORY_SEPARATOR . 'src';
                    $composerLoader->addPsr4($module->namespace(), $path);
                    $moduleProvider = $module->namespace() . 'Module';
                    App::register($moduleProvider);
                }
            });

            $this->moduleLoaded = true;
        }

        return $this;
    }

独自モジュールの作成

https://github.com/avored/framework/blob/master/src/Modules/Console/ModuleMakeCommand.php

実装はシンプルで、ダミーファイル(スタブと表現している)を取得して、仮テキストをコマンド実行者が入力した情報に置換してファイルを作成しているだけ。

BaseRepository

https://github.com/avored/framework/blob/master/src/Database/Repository/BaseRepository.php

CRUDメソッドを実装

<?php

namespace AvoRed\Framework\Database\Repository;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

abstract class BaseRepository
{
    /**
     * Per Page
     * @var int $perPage
     */
    public $perPage = 10;
    /**
     * All the Repository class must have an model method which should return the Model Class
     * 
     */
    abstract function model();

    /**
     * Get Query Builder of the model
     * @param int $perPage
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function query(): Builder
    {
        return $this->model()->query();
    }

    /**
     * Get Pagination of the model
     * @param int $perPage
     * @param array $with
     * @return Illuminate\Pagination\LengthAwarePaginator
     */
    public function paginate($perPage = 10, array $with = []) : LengthAwarePaginator
    {
        $this->perPage = $perPage;
        $query = $this->query();
        if (count($with) > 0) {
            return $query->with($with)->paginate($perPage);
        }
        return $query->paginate($perPage);
    }

    /**
     * Create Model Resource into a database.
     * @param array $data
     * @return \AvoRed\Framework\Database\Models\BaseModel $model
     */
    public function create(array $data)
    {
        return $this->model()->create($data);
    }

    /**
     * Find Model Resource into a database.
     * @param int $id
     * @return \AvoRed\Framework\Database\Models\Model $category
     */
    public function find(int $id)
    {
        return $this->model()->find($id);
    }

    /**
     * Delete Model Resource from a database.
     * @param int $id
     * @return int
     */
    public function delete(int $id) : int
    {
        return $this->model()->delete($id);
    }

    /**
     * Get All Models Collection from the database.
     * @return \Illuminate\Database\Eloquent\Collection $models
     */
    public function all() : Collection
    {
        return $this->model()->all();
    }

}

Middleareで共通処理の実行

middlwareの中で共通処理をしている。以下では
\AvoRed\Framework\Support\Middleware\AvoRedCore::class,
初期設定されている値、通貨の種類を取得して、セッションに格納している。

app/app/Http/Kernel.php

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \AvoRed\Framework\Support\Middleware\AvoRedCore::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

app/vendor/avored/framework/src/Support/Middleware/AvoRedCore.php

<?php

namespace AvoRed\Framework\Support\Middleware;

use Closure;
use Illuminate\Support\Facades\Session;
use AvoRed\Framework\Database\Contracts\CurrencyModelInterface;

class AvoRedCore
{
    /**
     * @var \AvoRed\Framework\Database\Repository\CurrencyRepository
     */
    protected $currencyRepository;

    /**
     * AvoRed Core Middleware Construct.
     * @param \AvoRed\Framework\Database\Contracts\CurrencyModelInterface $currencyRepository
     */
    public function __construct(CurrencyModelInterface $currencyRepository)
    {
        $this->currencyRepository = $currencyRepository;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->setDefaultCurrency();

        return $next($request);
    }

    /**
     * Set the Default Currency for the Application.
     * @return void
     */
    public function setDefaultCurrency()
    {
        if (! Session::has('default_currency')) {
            $currency = $this->currencyRepository->getDefault();
            Session::put('default_currency', $currency);
        }
        if (! Session::has('default_currency_symbol')) {
            $currency = $this->currencyRepository->getDefault();
            Session::put('default_currency_symbol', $currency->symbol);
        }
    }
}

if (! $value >= 1) {

こんな書き方あるんだ。
if ($value < 1)でもいいだろうけど。

<?php

namespace App\Http\Requests;

use illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Http\FormRequest as Request;

class CartRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'qty' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (! $value >= 1) {
                        $fail($attribute.' is invalid');
                    }
                },
            ],
        ];
    }
}