首頁  >  文章  >  php框架  >  使用Yii框架建立婚禮策劃網站

使用Yii框架建立婚禮策劃網站

WBOY
WBOY原創
2023-06-21 08:48:211437瀏覽

婚禮是每個人生命中的重要時刻,對多數人而言,一場美麗的婚禮是十分重要的。在策劃婚禮時,夫妻雙方注重的不僅是婚禮的規模和華麗程度,而更重視婚禮的細節和個人化體驗。為了解決這個問題,許多婚禮策劃公司成立並開發了自己的網站。本文將介紹如何使用Yii框架建立婚禮規劃網站。

Yii框架是一個高效能的PHP框架,其簡單易用的特點深受廣大開發者的喜愛。使用Yii框架,我們能夠更有效率地開發出一個高品質的網站。以下將介紹如何使用Yii框架建立婚禮策劃網站。

第一步:安裝Yii框架
首先,我們需要安裝Yii框架。可透過composer進行安裝:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic

或下載Yii框架壓縮包,解壓縮至伺服器目錄下。解壓縮後,執行下列指令安裝所需依賴:

php composer.phar install

第二步:建立資料庫及對應表
在上一個步驟中,我們已經成功安裝了Yii框架。接下來,需要建立資料庫及對應表。可以透過MySQL Workbench等工具直接建立。

建立一個名為wedding的資料庫,然後建立如下結構的表:

CREATE TABLE IF NOT EXISTS `user` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `username` VARCHAR(255) NOT NULL,
    `password_hash` VARCHAR(255) NOT NULL,
    `email` VARCHAR(255) NOT NULL,
    `auth_key` VARCHAR(255) NOT NULL,
    `status` SMALLINT NOT NULL DEFAULT 10,
    `created_at` INT NOT NULL,
    `updated_at` INT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `article` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `title` VARCHAR(255) NOT NULL,
    `content` TEXT NOT NULL,
    `status` SMALLINT NOT NULL DEFAULT 10,
    `created_at` INT NOT NULL,
    `updated_at` INT NOT NULL,
    `user_id` INT UNSIGNED NOT NULL,
    CONSTRAINT `fk_article_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

其中,user表儲存使用者信息,article表儲存文章資訊。

第三步:建立模型
在Yii框架中,模型是MVC架構中M(Model)的一部分,負責處理資料。我們需要建立User和Article兩個模型:

class User extends ActiveRecord implements IdentityInterface
{
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
}

class Article extends ActiveRecord
{
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
}

在上面的程式碼中,我們透過繼承ActiveRecord類別定義了User和Article兩個模型。 User模型實作了IdentityInterface接口,用於驗證;Article模型中透過getUser()方法定義了使用者和文章之間的關係。

第四步:建立控制器和視圖
在Yii框架中,控制器是MVC架構中C(Controller)的一部分,負責處理接收到的web請求。我們需要建立兩個控制器:UserController和ArticleController,以及對應的視圖。

UserController用於處理使用者註冊、登入等操作:

class UserController extends Controller
{
    public function actionSignup()
    {
        $model = new SignupForm();

        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            Yii::$app->session->setFlash('success', 'Thank you for registration. Please check your inbox for verification email.');
            return $this->goHome();
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionLogin()
    {
        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}

ArticleController用於處理文章編輯、顯示等操作:

class ArticleController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create', 'update'],
                'rules' => [
                    [
                        'actions' => ['create', 'update'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Article::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new Article();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

在上述程式碼中,我們使用了Yii內建的一些元件和操作,例如AccessControl、ActiveDataProvider、VerbFilter等,以更有效率地進行開發。

第五步:設定路由和資料庫
在Yii框架中,需要在設定檔中進行路由設定和資料庫連線設定。我們需要編輯如下兩個檔案:

/config/web.php:

return [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            'csrfParam' => '_csrf',
        ],
        'user' => [
            'identityClass' => 'appmodelsUser',
            'enableAutoLogin' => true,
        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'wedding_session',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yiilogFileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '' => 'article/index',
                '<controller>/<action>' => '<controller>/<action>',
                '<controller>/<action>/<id:d+>' => '<controller>/<action>',
            ],
        ],
        'db' => require __DIR__ . '/db.php',
    ],
    'params' => $params,
];

上面的程式碼中,需要設定資料庫、URL路由等信息,以便專案能夠順利運作。 /config/db.php檔案中則需要設定資料庫連線訊息,以便Yii框架與資料庫互動。

最後,我們還需要在/config/params.php中設定郵件發送訊息,以便用戶註冊成功後能夠收到驗證郵件。

到此,我們已經完成了使用Yii框架建立婚禮策劃網站的整個過程。透過本文的介紹,您已經了解了Yii框架的基本使用方法,以及如何建立一個簡單的婚禮策劃網站。如果您想要創建更複雜、更專業的婚禮網站,您還需要進一步深入學習Yii框架,以更有效率地開發web應用程式。

以上是使用Yii框架建立婚禮策劃網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn