Home >Backend Development >PHP Tutorial >Create testable and maintainable PHP code
Frameworks provide the tools for rapid application development, but often increase technical debt the faster you create functionality. Technical debt occurs when maintainability is not a purposeful focus for developers. Future changes and debugging are expensive due to lack of unit testing and structure.
Here's how to start structuring your code for testability and maintainability - and save you time.
Let's start with some contrived but typical code. This could be a model class in any given framework.
class User { public function getCurrentUser() { $user_id = $_SESSION['user_id']; $user = App::db->select('id, username') ->where('id', $user_id) ->limit(1) ->get(); if ( $user->num_results() > 0 ) { return $user->row(); } return false; } }
This code works, but needs improvement:
$_SESSION
global variable. Unit testing frameworks such as PHPUnit rely on the command line, where $_SESSION
and many other global variables are not available. App::db
instance used in the application. Also, what if we don't want the current user's information? Here is an attempt to create a unit test for the above functionality.
class UserModelTest extends PHPUnit_Framework_TestCase { public function testGetUser() { $user = new User(); $currentUser = $user->getCurrentUser(); $this->assertEquals(1, $currentUser->id); } }
Let's check it out. First, the test will fail. The $_SESSION
variable used in the User
object does not exist in the unit test because it runs PHP from the command line.
Secondly, there is no database connection setting. This means that in order to make this work, we need to bootstrap our application to get the App
object and its db
object. We also need a working database connection to test.
In order for this unit test to work, we need:
So, let’s start discussing how to improve this.
In this simple context, the function to retrieve the current user is unnecessary. This is a contrived example, but in the spirit of the DRY principle, the first optimization I chose to do was to generalize this approach.
class User { public function getUser($user_id) { $user = App::db->select('user') ->where('id', $user_id) ->limit(1) ->get(); if ( $user->num_results() > 0 ) { return $user->row(); } return false; } }
This provides a method that we can use throughout our application. Instead of passing the function to the model, we can pass in the current user when calling. Code is more modular and maintainable when it does not depend on other functionality, such as session global variables.
However, this still cannot be tested and maintained as intended. We still rely on database connections.
Let's help improve this situation by adding some dependency injection. When we pass the database connection into the class, our model might look like this.
class User { protected $_db; public function __construct($db_connection) { $this->_db = $db_connection; } public function getUser($user_id) { $user = $this->_db->select('user') ->where('id', $user_id) ->limit(1) ->get(); if ( $user->num_results() > 0 ) { return $user->row(); } return false; } }
Now, the dependencies for our User
model are provided. Our classes no longer assume a certain database connection, nor do they depend on any global objects.
At this point, our class is basically ready for testing. We can pass in a data source of our choice (mostly) and a user ID, and test the results of that call. We can also switch separate database connections (assuming both implement the same method of retrieving data). cool.
Let's see what a unit test might look like.
<?php use Mockery as m; use Fideloper\User; class SecondUserTest extends PHPUnit_Framework_TestCase { public function testGetCurrentUserMock() { $db_connection = $this->_mockDb(); $user = new User( $db_connection ); $result = $user->getUser( 1 ); $expected = new StdClass(); $expected->id = 1; $expected->username = 'fideloper'; $this->assertEquals( $result->id, $expected->id, 'User ID set correctly' ); $this->assertEquals( $result->username, $expected->username, 'Username set correctly' ); } protected function _mockDb() { // "Mock" (stub) database row result object $returnResult = new StdClass(); $returnResult->id = 1; $returnResult->username = 'fideloper'; // Mock database result object $result = m::mock('DbResult'); $result->shouldReceive('num_results')->once()->andReturn( 1 ); $result->shouldReceive('row')->once()->andReturn( $returnResult ); // Mock database connection object $db = m::mock('DbConnection'); $db->shouldReceive('select')->once()->andReturn( $db ); $db->shouldReceive('where')->once()->andReturn( $db ); $db->shouldReceive('limit')->once()->andReturn( $db ); $db->shouldReceive('get')->once()->andReturn( $result ); return $db; } }
I've added something new to this unit test: Mockery. Mockery allows you to "mock" (fake) PHP objects. In this example we are simulating a database connection. With our mock, we can skip testing the database connection and simply test our model.
Want to learn more about Mockery?
In this example, we are simulating a SQL connection. We tell the mock object to expect calls to the select
, where
, limit
, and get
methods. I return the Mock itself to reflect how the SQL connection object returns itself ($this
), making its method calls "chainable". Note that for the get
method I return the result of the database call - a stdClass
object populated with user data.
This solves some problems:
我们还可以做得更好。这就是它变得有趣的地方。
为了进一步改进这一点,我们可以定义并实现一个接口。考虑以下代码。
interface UserRepositoryInterface { public function getUser($user_id); } class MysqlUserRepository implements UserRepositoryInterface { protected $_db; public function __construct($db_conn) { $this->_db = $db_conn; } public function getUser($user_id) { $user = $this->_db->select('user') ->where('id', $user_id) ->limit(1) ->get(); if ( $user->num_results() > 0 ) { return $user->row(); } return false; } } class User { protected $userStore; public function __construct(UserRepositoryInterface $user) { $this->userStore = $user; } public function getUser($user_id) { return $this->userStore->getUser($user_id); } }
这里发生了一些事情。
addUser()
方法。User
模型中强制使用实现 UserInterface
的类。这样可以保证数据源始终有一个可用的 getUser()
方法,无论使用哪个数据源来实现 UserInterface
。请注意,我们的
User
对象类型提示UserInterface
在其构造函数中。这意味着实现UserInterface
的类必须传递到User
对象中。这是我们所依赖的保证 - 我们需要getUser
方法始终可用。
这样做的结果是什么?
User
类,我们可以轻松地模拟数据源。 (测试数据源的实现将是单独的单元测试的工作)。User
对象。如果您决定放弃 SQL,则只需创建一个不同的实现(例如 MongoDbUser
)并将其传递到您的 User
模型中。我们还简化了单元测试!
<?php use Mockery as m; use Fideloper\User; class ThirdUserTest extends PHPUnit_Framework_TestCase { public function testGetCurrentUserMock() { $userRepo = $this->_mockUserRepo(); $user = new User( $userRepo ); $result = $user->getUser( 1 ); $expected = new StdClass(); $expected->id = 1; $expected->username = 'fideloper'; $this->assertEquals( $result->id, $expected->id, 'User ID set correctly' ); $this->assertEquals( $result->username, $expected->username, 'Username set correctly' ); } protected function _mockUserRepo() { // Mock expected result $result = new StdClass(); $result->id = 1; $result->username = 'fideloper'; // Mock any user repository $userRepo = m::mock('Fideloper\Third\Repository\UserRepositoryInterface'); $userRepo->shouldReceive('getUser')->once()->andReturn( $result ); return $userRepo; } }
我们已经完全取消了模拟数据库连接的工作。相反,我们只是模拟数据源,并告诉它当调用 getUser
时要做什么。
但是,我们仍然可以做得更好!
考虑我们当前代码的用法:
// In some controller $user = new User( new MysqlUser( App:db->getConnection("mysql") ) ); $user->id = App::session("user->id"); $currentUser = $user->getUser($user_id);
我们的最后一步是引入容器。容器。在上面的代码中,我们需要创建并使用一堆对象来获取当前用户。此代码可能散布在您的应用程序中。如果您需要从 MySQL 切换到 MongoDB,您仍然需要编辑上述代码出现的每个位置。那几乎不是干的。容器可以解决这个问题。
容器只是“包含”一个对象或功能。它类似于应用程序中的注册表。我们可以使用容器自动实例化一个新的 User
对象以及所有需要的依赖项。下面,我使用 Pimple,一个流行的容器类。
// Somewhere in a configuration file $container = new Pimple(); $container["user"] = function() { return new User( new MysqlUser( App:db->getConnection('mysql') ) ); } // Now, in all of our controllers, we can simply write: $currentUser = $container['user']->getUser( App::session('user_id') );
我已将 User
模型的创建移至应用程序配置中的一个位置。结果是:
User
对象和选择的数据存储在我们应用程序的一个位置定义。User
模型从使用 MySQL 切换到 ONE 位置中的任何其他数据源。这更易于维护。在本教程的过程中,我们完成了以下任务:
我相信您已经注意到,我们以可维护性和可测试性的名义添加了更多代码。可以对这种实现提出强有力的论据:我们正在增加复杂性。事实上,这需要项目的主要作者和合作者对代码有更深入的了解。
但是,技术债务总体减少远远超过了解释和理解的成本。
您可以使用 Composer 轻松地将 Mockery 和 PHPUnit 包含到您的应用程序中。将这些添加到 composer.json
文件中的“require-dev”部分:
"require-dev": { "mockery/mockery": "0.8.*", "phpunit/phpunit": "3.7.*" }
然后,您可以按照“dev”要求安装基于 Composer 的依赖项:
$ php composer.phar install --dev
在 Nettuts+ 上了解有关 Mockery、Composer 和 PHPUnit 的更多信息。
对于 PHP,请考虑使用 Laravel 4,因为它特别利用了容器和此处介绍的其他概念。
感谢您的阅读!
The above is the detailed content of Create testable and maintainable PHP code. For more information, please follow other related articles on the PHP Chinese website!