CakePHP快速开发应用程序

tech2023-11-27  34

CakePHP is a framework that provides a solid base for PHP development. It allows users at any skill level to rapidly develop robust web applications. The framework follows the principles of the MVC pattern (Model-View-Controller) which separates your code in three parts:

CakePHP是一个框架,为PHP开发提供了坚实的基础。 它允许任何技能水平的用户快速开发强大的Web应用程序。 该框架遵循MVC模式(模型-视图-控制器)的原理,该模式将您的代码分为三个部分:

Model – code that deals with data (i.e. database, filesystem, and other data providers)

模型 –处理数据的代码(即数据库,文件系统和其他数据提供者)

View – code that displays data and deals with the interface (web pages, RSS feeds, etc.)

查看 –显示数据并处理界面(网页,RSS提要等)的代码

Controller – code that provides the application’s main functionality by collecting input coordinating the model and view code

控制器 –通过收集协调模型和视图代码的输入来提供应用程序主要功能的代码

CakePHP augments the pattern by adding a Dispatcher component as well to help with routing requests to an appropriate controller. The flow within a CakePHP application therefor looks like this:

CakePHP通过添加Dispatcher组件来增强模式,以帮助将请求路由到适当的控制器。 CakePHP应用程序中的流程如下所示:

You can find more information about the MVC pattern on the CakePHP Book site.

您可以在CakePHP Book网站上找到有关MVC模式的更多信息。

Personally, the reason why I prefer CakePHP over other PHP frameworks is its better support for console applications. CakePHP has a powerful console tool that can be customized to build applications for both the web and the console world.

就个人而言,之所以我选择CakePHP而不是其他PHP框架,是因为它更好地支持控制台应用程序。 CakePHP具有功能强大的控制台工具,可以对其进行自定义以构建用于Web和控制台世界的应用程序。

In this article I’ll introduce you to two of CakePHP’s most useful features:

在本文中,我将向您介绍CakePHP的两个最有用的功能:

automatic code generation using the console tool Bake

使用控制台工具Bake自动生成代码

dynamic scaffolding

动态脚手架

I’ll do so by recreating the example that Stephen Thorpe presented in his article Untangling MVC with CodeIgniter using these two features of CakePHP. Thorpe’s example application presents a form to collect an email address, validates the address, stores it to a database.

我将通过使用CakePHP的这两个功能,重新创建Stephen Thorpe在他的文章《 使用CodeIgniter解析MVC》中提出的示例来实现这一点。 索普(Thorpe)的示例应用程序提供了一种收集电子邮件地址,验证地址并将其存储到数据库的表格。

安装与配置 (Installation and Configuration)

Before you start to write any code, you’ll need to download and install the latest version of CakePHP from the CakePHP website. Make sure that your web server supports URL rewriting (Apache does so through mod_rewrite for example) as it is heavily used by CakePHP. There are other fallback methods, but they are outside the scope of this article.

在开始编写任何代码之前,您需要从CakePHP网站下载并安装最新版本的CakePHP。 确保您的Web服务器支持URL重写(例如,Apache通过mod_rewrite支持),因为CakePHP大量使用了URL重写。 还有其他后备方法,但它们不在本文讨论范围之内。

After obtaining the CakePHP code:

获取CakePHP代码后:

Uncompress the archive file in the document root of your web server and rename the directory to Subscribers.

解压缩Web服务器文档根目录中的存档文件,并将目录重命名为Subscribers 。

Make the directory Subscribers/app/tmp writable to the user account under which the web server runs.

将目录Subscribers/app/tmp可运行Web服务器的用户帐户。

Open your browser and navigate to the Subscribers directory (for example http://localhost/Subscribers/).

打开浏览器并导航到Subscribers目录(例如http://localhost/Subscribers/ )。

You should see a page similar to the following:

您应该看到类似于以下内容的页面:

The philosophy of CakePHP is “convention over configuration.” If you follow CakePHP’s basic naming conventions for classes, variables, file names, and paths, you can minimize your configuration files to essential information.

CakePHP的理念是“约定超越配置”。 如果遵循CakePHP关于类,变量,文件名和路径的基本命名约定,则可以将配置文件最小化为基本信息。

The directory app/Config is one of CakePHP’s conventions. In this directory you’ll find the default configuration files and can add your specific files as necessary. CakePHP provides some basic settings inside the core.php file, and you can override these setting by editing the bootstrap.php file which is intended to be specific for your application. CakePHP also provides a sample file for database configuration called database.php.default.

app/Config目录是CakePHP的约定之一。 在此目录中,您将找到默认配置文件,并可以根据需要添加特定文件。 CakePHP在core.php文件中提供了一些基本设置,您可以通过编辑专门针对您的应用程序的bootstrap.php文件来覆盖这些设置。 CakePHP还提供了一个名为database.php.default数据库配置示例文件。

安全变更 (Security Changes)

In the initial browser output you should see two red notices asking you to edit the parameters Security.salt and Security.cipherSeed. These two settings are used by the framework for all of its encryption routines, so it’s obviously better to have values different from the shipped defaults.

在浏览器的初始输出中,您应该看到两个红色的提示,要求您编辑参数Security.salt和Security.cipherSeed 。 框架对其所有加密例程都使用了这两个设置,因此,最好使值与出厂默认值不同。

Open the app/Config/bootstrap.php file and insert these two lines:

打开app/Config/bootstrap.php文件并插入以下两行:

<?php Configure::write('Security.salt', 'SomeSuperSecretLongStringHere'); Configure::write('Security.cipherSeed', 'SomeSuperSecretLongNumberHere');

CakePHP uses its Configure class to manage such settings. With these lines, you use Configure‘s write() static method to set the new values. The values will be stored in memory within the configuration object. Another method you’ll use often is Configure::read() to retrieve the application’s settings. The convention of using Section.variableName to name settings is called dot notation and it’s converted internally by CakePHP into an associative array.

CakePHP使用其Configure类来管理此类设置。 在这些行中,您可以使用Configure的write()静态方法来设置新值。 这些值将存储在配置对象内的内存中。 您将经常使用的另一种方法是Configure::read()来检索应用程序的设置。 使用Section.variableName命名设置的约定称为点符号 ,它由CakePHP在内部转换为关联数组。

Now if you reload the page the two red notices disappear.

现在,如果您重新加载页面,则两个红色通知会消失。

数据库配置 (Database Configuration)

The yellow notice suggests how to proceed to configure database connectivity: rename (or copy) app/Config/database.php.default to app/Config/database.php and open it in your editor.

黄色通知表示如何继续配置数据库连接:将app/Config/database.php.default重命名(或复制)到app/Config/database.php并在编辑器中将其打开。

The DATABASE_CONFIG class stores details for all database connections inside its public properties. The starter file provides you with the $default and $test properties (the first is used by default by the application, and the latter is used optionally for PHPUnit tests).

DATABASE_CONFIG类在其公共属性内存储所有数据库连接的详细信息。 初始文件为您提供了$default和$test属性(应用程序默认使用前一个属性,而PHPUnit测试则可以选择使用后者)。

Each variable is an associative array of settings that should be familiar to you: hostname, login, password, database, and prefix. The datasource key sets which database driver to use and the default is MySQL (Database/Mysql). CakePHP uses PDO and so it also supports Postgres, SQLite, and MS SQL Server. Additionally, you can add custom datasources or override existing ones. I’ll continue demonstrating with the default MySQL driver.

每个变量都是您应该熟悉的一组关联设置: hostname , login hostname , password , database和prefix 。 数据源键设置要使用的数据库驱动程序,默认为MySQL( Database/Mysql )。 CakePHP使用PDO,因此它还支持Postgres,SQLite和MS SQL Server。 此外,您可以添加自定义数据源或覆盖现有数据源。 我将继续使用默认MySQL驱动程序进行演示。

Create a new database on you server (i.e. cake_subscribers) and insert the connection details in your $default connection. Reload the page and you should see a green notice saying “Cake is able to connect to the database.”

在您的服务器上创建一个新数据库(即cake_subscribers ),并将连接详细信息插入$default连接中。 重新加载页面,您应该会看到绿色的通知,指出“ Cake能够连接到数据库。”

You’ll also need a database table to save the subscriber information, so use the following to create the table subscribers:

您还需要一个数据库表来保存订户信息,因此请使用以下命令创建表订户:

CREATE TABLE subscribers ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(128) NOT NULL, last_name VARCHAR(128) NOT NULL, email VARCHAR(128) NOT NULL UNIQUE, created DATETIME, modified DATETIME )

其他有用的设置 (Other Useful Settings)

Looking inside the core.php file you can see other interesting settings that can be overridden with the bootstrap.php file: sessions and logging features, error and exception handling, and more. One useful setting is the debug level. The default value is 2, which means that errors and warnings are displayed, cache is always refreshed, and the full SQL output is shown at the bottom of each page. A value of 1 will suppress the SQL output. A value of 0 is suitable for production; only errors are logged and CakePHP-specific exceptions are displayed gracefully as 404 or 501 errors.

在core.php文件中,您可以看到可以由bootstrap.php文件覆盖的其他有趣设置:会话和日志记录功能,错误和异常处理等。 一种有用的设置是调试级别。 默认值为2,这表示显示错误和警告,始终刷新高速缓存,并且完整SQL输出显示在每个页面的底部。 值为1将禁止SQL输出。 值0适用于生产。 仅记录错误,并且CakePHP特定的异常正常显示为404或501错误。

烘焙代码生成 (Code Generation with Bake)

Once you have the basic environment set up, you can start coding or… let CakePHP write some code for you! The Bake console tool is very powerful. It can generate any of the basic components (models, views, and controllers) and other useful things like unit tests.

一旦设置了基本环境,就可以开始编码,或者…让CakePHP为您编写一些代码! Bake控制台工具非常强大。 它可以生成任何基本组件(模型,视图和控制器)以及其他有用的东西,例如单元测试。

Open a terminal window and navigate to your project’s directory (for example, /Users/Shared/WebServer/Documents/Subscribers) and run the Bake command as shown here to generate code for the model:

打开一个终端窗口并导航到项目的目录(例如/Users/Shared/WebServer/Documents/Subscribers ),然后运行Bake命令(如下所示)为模型生成代码:

Vitos-Laptop:Subscribers vito$ lib/Cake/Console/cake/bake model Welcome to CakePHP v2.0.5 Console --------------------------------------------------------------- App : app Path: /Users/Shared/WebServer/Documents/Subscribers/app/ --------------------------------------------------------------- --------------------------------------------------------------- Bake Model Path: /Users/Shared/WebServer/Documents/Subscribers/app/Model/ --------------------------------------------------------------- Use Database Config: (default/test) [default] >

Press enter to confirm your default database connection and you’ll see:

按Enter确认默认数据库连接,您将看到:

Possible Models based on your current database: 1. Subscriber Enter a number from the list above, type in the name of another model, or 'q' to exit [q] >

Enter 1, and then Bake will ask if you want to specify validation criteria for this model. Enter Y.

输入1,然后Bake会询问您是否要为此模型指定验证条件。 输入Y。

For each field, Bake asks you to select one or more validation rules and suggests you the most suitable. Chose notempty for the name and last_name fields and email for the email field.

对于每个字段,Bake要求您选择一个或多个验证规则,并建议您最合适的。 选择notempty的name和last_name字段和email的电子邮件领域。

The last question is about model associations, and it is safe to Enter N for now. You should see a recap:

最后一个问题是关于模型关联的,现在输入N是安全的。 您应该看到一个回顾:

--------------------------------------------------------------- The following Model will be created: --------------------------------------------------------------- Name: Subscriber DB Table: `subscribers` Validation: Array ( [name] => Array ( [notempty] => notempty ) [last_name] => Array ( [notempty] => notempty ) [email] => Array ( [email] => email ) ) --------------------------------------------------------------- Look okay? (y/n)

If it’s all right, Enter Y and let it work. In less than one minute we have a model class, complete with validation and testing features. Give it a look in your editor. Awesome!

如果可以,请输入Y并使其生效。 在不到一分钟的时间内,我们有了一个模型类,其中包含验证和测试功能。 在您的编辑器中看一下。 太棒了!

Now let’s do the same thing for the controller:

现在让我们为控制器做同样的事情:

Vitos-Laptop:Subscribers vito$ lib/Cake/Console/cake/bake controller

Press enter to accept the default database configuration, then select the Subscribers controller, then enter Y to build the controller interactively and then Y to enable dynamic scaffolding. The final output should look like this:

按Enter键接受默认的数据库配置,然后选择“ Subscribers控制器,然后输入Y以交互方式构建控制器,然后输入Y以启用动态支架。 最终输出应如下所示:

--------------------------------------------------------------- The following controller will be created: --------------------------------------------------------------- Controller Name: Subscribers public $scaffold; --------------------------------------------------------------- Look okay? (y/n) [y] >

具有脚手架的自动用户界面 (Automatic User Interfaces with Scaffolding)

If you open the controller file app/Controller/SubscribersController.php you’ll see that it’s almost empty; there is a class definition and a public property named $scaffold. Bake can generate the full code for controllers and can also generate views (and I encourage you to try), but we chose earlier to use the dynamic scaffolding feature.

如果打开控制器文件app/Controller/SubscribersController.php您会发现它几乎是空的。 有一个类定义和一个名为$scaffold的公共属性。 Bake可以为控制器生成完整的代码,也可以生成视图(我鼓励您尝试一下),但是我们较早选择使用动态脚手架功能。

Scaffolding is a technique that allows you to define and create a basic application that can create, retrieve, update and delete objects. All you need to use scaffolding is a model and a controller. Skeptical? Point your browser to http://localhost/Subscribers/subscribers and you should see this:

脚手架是一种允许您定义和创建可以创建,检索,更新和删除对象的基本应用程序的技术。 您需要使用脚手架的是模型和控制器。 怀疑吗? 将浏览器指向http://localhost/Subscribers/subscribers ,您应该看到以下内容:

The interface is fully functional! Try to insert and edit some entries; you’ll see error handling in action and full pagination.

接口功能齐全! 尝试插入和编辑一些条目; 您会看到实际操作中的错误处理和完整的分页。

But if you try to insert a duplicated email address you should see a very bad (but elegant) error message. This happens because I applied the UNIQUE index to the email field in the database and CakePHP doesn’t know this. Open the model file app/Model/Subscriber.php and edit its email validation rule like this:

但是,如果您尝试插入重复的电子邮件地址,则应该看到一个非常糟糕(但优雅)的错误消息。 发生这种情况是因为我将UNIQUE索引应用于数据库中的email字段,而CakePHP不知道这一点。 打开模型文件app/Model/Subscriber.php并编辑其电子邮件验证规则,如下所示:

<?php ... 'email' => array( 'email' => array( 'rule' => array('email'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'unique' => array( 'rule' => array('isUnique'), 'message' => 'This email address is already registered', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ),

Now try adding a duplicate address again and this time you should see a more friendly error message.

现在,尝试再次添加重复的地址,这一次您应该会看到一条更友好的错误消息。

Scaffolding can also be redirected to a specific path, for example /admin. You can build and customize the public pages of an application and use the scaffolding feature for the private administration panel, preferably using one of CakePHP’s authentication, authorization, and security features. I’ll show you the first step and then let you explore the others.

脚手架也可以重定向到特定路径,例如/admin 。 您可以构建和自定义应用程序的公共页面,并将脚手架功能用于私有管理面板,最好使用CakePHP的身份验证,授权和安全功能之一。 我将向您展示第一步,然后让您探索其他步骤。

Add this line to your bootstrap.php file:

将此行添加到bootstrap.php文件中:

<?php Configure::write('Routing.prefixes', array('admin'));

This tells CakePHP to parse admin as an URL prefix (you can use as many prefixes you want). Then in the SubscribersController.php file edit the scaffold property like this:

这告诉CakePHP将admin解析为URL前缀(您可以使用任意多个前缀)。 然后在SubscribersController.php文件中编辑scaffold属性,如下所示:

<?php ... public $scaffold = 'admin';

If you reopen the subscribers index URL you should see an error, but if you point to http://localhost/Subscribers/admin/subscribers you see your administration panel.

如果重新打开订户索引URL,应该会看到错误,但是如果指向http://localhost/Subscribers/admin/subscribers则会看到管理面板。

摘要 (Summary)

In this introductory article, you have seen only the tip of the iceberg of CakePHP’s capabilities. CakePHP has a lot of features and nearly each of them is extensible and customizable to suit your needs. In addition, you can count on a very useful documentation, a complete API reference and an active community called The Bakery. I suggest you to start with the tutorials and… Happy Baking!

在这篇介绍性文章中,您仅看到CakePHP功能的冰山一角。 CakePHP具有很多功能,几乎每个功能都可以扩展和定制,以满足您的需求。 此外,您可以依靠非常有用的文档 ,完整的API参考以及称为The Bakery的活跃社区。 我建议您从教程开始,然后……快乐烘焙!

Image via sutsaiy / Shutterstock

图片来自sutsaiy / Shutterstock

翻译自: https://www.sitepoint.com/rapid-application-development-with-cakephp/

相关资源:debug_kit:CakePHP应用程序的调试工具栏-源码
最新回复(0)