Windowsで始めるCakePHP4

CakePHP4のメモ

118 views

ユーザーを追加する場合のクリーンアーキテクチャ①

クリーンアーキテクチャを使って、ユーザーテーブルに新しいユーザーを追加する場合のCakePHP4のサンプルコードを概略的に示す。

エンティティ層

// src/Model/Entity/User.php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];
}

ユースケース層

新しいユーザーを追加するサービスを定義します。

// src/Service/UserService.php

namespace App\Service;

use App\Model\Entity\User;
use App\Model\Table\UsersTable;

class UserService {
    private $usersTable;

    public function __construct(UsersTable $usersTable) {
        $this->usersTable = $usersTable;
    }

    public function addUser($data): User {
        $user = $this->usersTable->newEntity($data);
        $this->usersTable->save($user);
        return $user;
    }
}

インターフェースアダプタ層

データベースの操作に関連するロジックを扱います。

// src/Model/Table/UsersTable.php

namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table {
    public function initialize(array $config): void {
        $this->setEntityClass(User::class);
    }
}

フレームワーク&ドライバ層

// src/Controller/UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use App\Service\UserService;

class UsersController extends AppController {
    private $userService;

    public function initialize(): void {
        parent::initialize();
        $this->userService = new UserService($this->loadModel());
    }

    public function add() {
        if ($this->request->is('post')) {
            $data = $this->request->getData();
            $user = $this->userService->addUser($data);
            $this->set('user', $user);
        }
    }
}

edit,delete,indexも追加した場合

UserServiceクラスの例。

namespace App\Service;

use App\Model\Entity\User;
use App\Model\Table\UsersTable;

class UserService {
    private $usersTable;
    private $lastErrors = [];

    public function __construct(UsersTable $usersTable) {
        $this->usersTable = $usersTable;
    }

    // ... addUser, getErrors ...

    public function editUser($id, $data): bool {
        $user = $this->usersTable->get($id);
        $this->usersTable->patchEntity($user, $data);
        if ($this->usersTable->save($user)) {
            return true;
        } else {
            $this->lastErrors = $user->getErrors();
            return false;
        }
    }

    public function deleteUser($id): bool {
        $user = $this->usersTable->get($id);
        if ($this->usersTable->delete($user)) {
            return true;
        } else {
            $this->lastErrors = $user->getErrors();
            return false;
        }
    }

    public function getUser($id): ?User {
        return $this->usersTable->get($id);
    }

    public function getAllUsers(): array {
        return $this->usersTable->find()->all();
    }
}

UsersControllerの例。

namespace App\Controller;

use App\Controller\AppController;
use App\Service\UserService;

class UsersController extends AppController {
    private $userService;

    public function initialize(): void {
        parent::initialize();
        $this->userService = new UserService($this->loadModel());
    }

    // ... add ...

    public function edit($id) {
        $user = $this->userService->getUser($id);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->getData();
            if ($this->userService->editUser($id, $data)) {
                $this->Flash->success(__('User has been updated.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $errors = $this->userService->getErrors();
                $this->Flash->error(__('Unable to update user.'));
            }
        }
        $this->set('user', $user);
    }

    public function delete($id) {
        $this->request->allowMethod(['post', 'delete']);
        if ($this->userService->deleteUser($id)) {
            $this->Flash->success(__('User with id {0} has been deleted.', $id));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('Unable to delete user.'));
        }
    }

    public function index() {
        $users = $this->userService->getAllUsers();
        $this->set('users', $users);
    }
}

この方法で、UserServiceはビジネスロジックを一貫して管理し、UsersControllerはユーザインターフェイスのロジックとのやりとりを担当する、という役割分担がはっきりとします。これにより、コードの再利用性やテスト性が向上し、ビジネスロジックの変更や拡張が容易になります。

Page 15 of 17.

前のページ 次のページ



[添付ファイル]

1.php_xdebug-3.0.4-8.0-vs16-x86_64.dll  


お問い合わせ

プロフィール

マッスル

自己紹介

本サイトの作成者。
趣味:プログラム/水耕栽培/仮想通貨/激辛好き
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
仮想通貨はNEMが好き。
水耕栽培は激辛好きが高じて、キャロライナ・リーパーの栽培にチャレンジ中。

サイト/ブログ

https://www.osumoi-stdio.com/pyarticle/

ツイッター

@darkimpact0626