您的位置:首页 > 编程语言 > PHP开发

如何快速搭建一个CakePHP项目

2017-03-02 14:33 791 查看

安装Composer

Composer是一个基于PHP平台的包依赖管理器,具体安装方式可参考:https://getcomposer.org/

使用Composer生成CakePHP项目

Composer安装成功后,使用CMD执行类似如下Composer命令,生成一个空的CakePHP项目:

D:\cakeprojects>composer create-project --prefer-dist cakephp/app cakeblog


以上命令将在D盘下的cakeprojects目录下生成一个名为cakeblog的项目,并包含如下目录结构:

/cakeblog
/bin
/config
/logs
/plugins
/src
/tests
/tmp
/vendor
/webroot
.editorconfig
.gitignore
.htaccess
.travis.yml
composer.json
index.php
phpunit.xml.dist
README.md


创建数据表

创建一个名为cake_blog的数据库,并执行以下MySQL语句生成相关数据表:

/* First, create our articles table: */
CREATE TABLE articles (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);

/* Then insert some articles for testing: */
INSERT INTO articles (title,body,created)
VALUES ('The title', 'This is the article body.', NOW());
INSERT INTO articles (title,body,created)
VALUES ('A title once again', 'And the article body follows.', NOW());
INSERT INTO articles (title,body,created)
VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());


数据表和字段的命名需要符合CakePHP的命名约定

修改配置文件

项目根目录下的config/app.php文件是全局配置文件,对其中关于数据库配置的部分进行修改,改成自己使用的数据库名称、用户名及密码等。

'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
/**
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '123456',
'database' => 'cake_blog',
'encoding' => 'utf8',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => true,
'log' => false,

......
]


用bake命令生成脚手架程序

首先使用Composer执行以下命令安装Bake包:

composer require --dev cakephp/bake:~1.0


安装成功后,在项目bin目录下执行如下命令,会列出Bake所有有效的命令。

D:\cakeprojects\cakeblog\bin>cake bake


然后执行Bake命令,生成基于articles表的脚手架程序,包括Table类、Entity类、Controller类以及index、view、add、edit视图文件等。

D:\cakeprojects\cakeblog\bin>cake bake all articles


实现基本的增删改查功能

在浏览器访问:http://localhost/cakeprojects/cakeblog/articles,默认显示articles列表,并包含基本的增删改查操作链接。另外,CakePHP提供了一套默认的基础样式。



补充:CakePHP要求开启Apache的rewrite_module模块,并确保项目目录下的log和tmp目录可读写。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cakephp php composer