萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

CakePHP 入門完整指南:從安裝配置到第一個 MVC 應用實戰

前言:為什麼選擇 CakePHP?

CakePHP 是 PHP 陣營經典的 MVC 框架,特點是慣例優於配置、內建代碼生成(Bake)、強大的 ORM、靈活的路由與驗證。對初學者友善,同時具備企業級專案所需的擴充性。本文以 CakePHP 3.x/4.x 為基準(原文為 1.2 版,已過時),提供現代化安裝與入門流程。

環境需求

  • PHP 7.4+ / 8.x
  • Composer
  • 資料庫:MySQL 5.7+ / PostgreSQL / SQLite
  • Web Server:Nginx + PHP-FPM 或 Apache + mod_rewrite
  • 擴充:mbstring, intl, pdo_mysql, gd/imagick

安裝專案

# 使用 Composer 建立專案(建議目錄名稱避免中文、空格)
composer create-project --prefer-dist cakephp/app:4.* my_app

# 進入專案目錄
cd my_app

# 設定資料庫連線(修改 config/app_local.php)
# 'Datasources' => [
#     'default' => [
#         'className' => 'Cake\Database\Connection',
#         'driver' => 'Cake\Database\Driver\Mysql',
#         'persistent' => false,
#         'host' => 'localhost',
#         'username' => 'your_user',
#         'password' => 'your_pass',
#         'database' => 'cake_blog',
#         'encoding' => 'utf8mb4',
#         'timezone' => 'UTC',
#         'cacheMetadata' => true,
#     ],
# ],

資料庫遷移與種子資料

# 建立遷移檔
bin/cake bake migration CreateArticles title:string body:text published:boolean created modified

# 執行遷移
bin/cake migrations migrate

# 建立種子資料
bin/cake bake seed Articles
# 編輯 config/Seeds/ArticlesSeed.php
# 執行種子
bin/cake migrations seed

快速生成 MVC 骨架:Bake 指令

# 一鍵生成 Model、Controller、Template、測試、Fixture
bin/cake bake all Articles

# 或分別生成
bin/cake bake model Articles
bin/cake bake controller Articles
bin/cake bake template Articles

核心檔案結構解析


my_app/
├── bin/                    # 執行腳本
├── config/                 # 設定檔
│   ├── app.php             # 核心設定
│   ├── app_local.php       # 本地覆蓋(不進版控)
│   ├── routes.php          # 路由設定
│   └── bootstrap.php       # 啟動引導
├── plugins/                # 外掛
├── src/
│   ├── Controller/         # 控制器
│   │   ├── AppController.php
│   │   └── ArticlesController.php
│   ├── Model/
│   │   ├── Table/          # Table 類別(資料存取)
│   │   │   └── ArticlesTable.php
│   │   └── Entity/         # Entity 類別(單筆資料)
│   │       └── Article.php
│   ├── View/               # 模板
│   │   └── Articles/
│   │       ├── index.php
│   │       ├── view.php
│   │       ├── add.php
│   │       └── edit.php
│   └── Shell/              # CLI 命令
├── templates/              # 佈局、元素、錯誤頁
├── tests/                  # 測試
├── tmp/                    # 快取、日誌、Session(需可寫)
├── vendor/                 # Composer 套件
└── webroot/                # 公開目錄(DocumentRoot 指向這裡)
    ├── index.php           # 入口點
    ├── css/, js/, img/
    └── .htaccess           # URL 重寫規則

關鍵程式碼解析

1. Table 類別:資料存取與業務邏輯

<?php
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        $this->setTable('articles');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        // 關聯
        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('Comments');
    }

    public function validationDefault(Validator $validator): Validator
    {
        return $validator
            ->notEmptyString('title', '標題不可為空')
            ->maxLength('title', 255)
            ->notEmptyString('body', '內容不可為空')
            ->add('published', 'boolean', ['rule' => 'boolean']);
    }

    // 自定義查詢方法
    public function findPublished(\Cake\ORM\Query $query, array $options)
    {
        return $query->where(['published' => true])
                     ->orderDesc('created');
    }
}

2. Entity 類別:單筆資料與存取器

<?php
// src/Model/Entity/Article.php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Article extends Entity
{
    protected $_accessible = [
        'title' => true,
        'body' => true,
        'published' => true,
        'user_id' => true,
        'created' => true,
        'modified' => true,
    ];

    // 虛擬屬性:閱讀時間估算
    protected function _getReadingTime(): int
    {
        $words = str_word_count(strip_tags($this->body));
        return max(1, (int)ceil($words / 200)); // 假設每分鐘 200 字
    }

    // 存取器:自動轉換 Markdown
    protected function _setBody(string $value): string
    {
        // 這裡可整合 Parsedown 等庫
        return $value;
    }
}

3. Controller:處理請求、協調 Model 與 View

<?php
// src/Controller/ArticlesController.php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Http\Exception\NotFoundException;

class ArticlesController extends AppController
{
    public function index()
    {
        $query = $this->Articles->find('published');
        $articles = $this->paginate($query, ['limit' => 10]);
        $this->set(compact('articles'));
    }

    public function view($id = null)
    {
        $article = $this->Articles->get($id, [
            'contain' => ['Users', 'Comments'],
        ]);
        $this->set(compact('article'));
    }

    public function add()
    {
        $article = $this->Articles->newEmptyEntity();
        if ($this->request->is('post')) {
            $article = $this->Articles->patchEntity($article, $this->request->getData());
            $article->user_id = $this->Authentication->getIdentity()->getIdentifier(); // 需 Authentication plugin
            if ($this->Articles->save($article)) {
                $this->Flash->success('文章已發布');
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error('發布失敗,請檢查輸入');
        }
        $this->set(compact('article'));
    }

    public function edit($id = null)
    {
        $article = $this->Articles->get($id, ['contain' => []]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $article = $this->Articles->patchEntity($article, $this->request->getData());
            if ($this->Articles->save($article)) {
                $this->Flash->success('文章已更新');
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error('更新失敗');
        }
        $this->set(compact('article'));
    }

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $article = $this->Articles->get($id);
        if ($this->Articles->delete($article)) {
            $this->Flash->success('文章已刪除');
        } else {
            $this->Flash->error('刪除失敗');
        }
        return $this->redirect(['action' => 'index']);
    }
}

4. 模板:Twig 風格的 PHP 模板

<!-- templates/Articles/index.php -->
<h1>文章列表</h1>

<table class="table">
    <thead>
        <tr><th>標題</th><th>作者</th><th>建立時間</th><th>操作</th></tr>
    </thead>
    <tbody>
    <?php foreach ($articles as $article): ?>
        <tr>
            <td><?= $this->Html->link(h($article->title), ['action' => 'view', $article->id]) ?></td>
            <td><?= h($article->user->username ?? 'N/A') ?></td>
            <td><?= $article->created->format('Y-m-d H:i') ?></td>
            <td>
                <?= $this->Html->link('編輯', ['action' => 'edit', $article->id], ['class' => 'btn btn-sm btn-outline-primary']) ?>
                <?= $this->Form->postLink('刪除', ['action' => 'delete', $article->id], [
                    'class' => 'btn btn-sm btn-outline-danger',
                    'confirm' => '確定刪除?',
                ]) ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?= $this->Paginator->prev('上一頁') ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next('下一頁') ?>

路由設定

<?php
// config/routes.php
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
    $routes->connect('/articles', ['controller' => 'Articles', 'action' => 'index']);
    $routes->connect('/articles/:action/*', ['controller' => 'Articles']);
    $routes->fallbacks(DashedRoute::class);
});

// RESTful 資源路由
Router::scope('/api', function (RouteBuilder $routes) {
    $routes->setExtensions(['json']);
    $routes->resources('Articles', ['map' => [
        'delete' => ['action' => 'delete', 'method' => 'DELETE'],
    ]]);
});

Web Server 設定

Nginx + PHP-FPM


server {
    listen 80;
    server_name cake.test;
    root /path/to/my_app/webroot;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Apache + mod_rewrite


<VirtualHost *:80>
    DocumentRoot "/path/to/my_app/webroot"
    ServerName cake.test

    <Directory "/path/to/my_app/webroot">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

確保 webroot/.htaccess 存在(Composer create-project 會自動產生)。

常見問題排查

現象原因解決
首頁顯示「A Database connection is missing」config/app_local.php 資料庫設定錯誤檢查 host、username、password、database;確認 MySQL 服務運行
CSS/JS 404DocumentRoot 未指向 webroot/、rewrite 失效修正 Web Server 設定、確認 .htaccess 存在
tmp/ 權限錯誤快取/日誌目錄不可寫chmod -R 777 tmp/ logs/(開發環境)
Bake 指令找不到 Table資料表命名不符慣例(複數、snake_case)手動建立 Table/Entity 或調整資料表命名

學習路徑建議

  1. 完成官方 Bookmarks Tutorial(書籤應用)
  2. 閱讀 官方 Cookbook 核心章節:ORM、驗證、認證、測試
  3. 實作一個部落格系統:文章 CRUD、分類標籤、使用者認證、評論、RSS、搜尋
  4. 學習單元測試:PHPUnit + CakePHP TestSuite(Fixture、Controller 整合測試)
  5. 探索外掛生態:Authentication、Authorization、DebugKit、Migrations、Queue

總結

CakePHP 以「慣例優於配置」降低決策疲勞,Bake 代碼生成 加速開發,ORM + Entity 提供優雅的資料操作體驗。從 composer create-project 到第一個 CRUD 應用,只需幾分鐘。掌握 Table/Entity/Controller/Template 四大核心、路由與遷移機制,即可駕馭中型專案。建議搭配 PHPStan 靜態分析、PHPUnit 測試、GitHub Actions CI 建立專業開發流程。

copyright © 萬盛學電腦網 all rights reserved