Home >Backend Development >PHP Tutorial >Create testable and maintainable PHP code

Create testable and maintainable PHP code

王林
王林Original
2023-08-29 22:01:08866browse

创建可测试和可维护的 PHP 代码

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.


We will (loosely) cover

  1. dry
  2. Dependency Injection
  3. interface
  4. container
  5. Use PHPUnit for unit testing

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:

  1. This is not testable.
    • We rely on the $_SESSION global variable. Unit testing frameworks such as PHPUnit rely on the command line, where $_SESSION and many other global variables are not available.
    • We rely on database connections. Ideally, actual database connections should be avoided in unit tests. Testing is about code, not data.
  2. The maintainability of this code is not ideal. For example, if we change the data source, we need to change the database code in every App::db instance used in the application. Also, what if we don't want the current user's information?

Attempted unit tests

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:

  1. Set up the configuration for the CLI (PHPUnit) running in our application
  2. Depends on database connection. Doing this means relying on a data source separate from our unit tests. What if our test database doesn't have the data we expect? What if our database connection is slow?
  3. Applications that rely on bootstrapping can significantly slow down unit testing by adding overhead to testing. Ideally, most of our code can be tested independently of the framework used.

So, let’s start discussing how to improve this.


Keep your code dry

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.


Dependency Injection

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:

  1. 我们仅测试我们的模型类。我们还没有测试数据库连接。
  2. 我们能够控制模拟数据库连接的输入和输出,因此可以可靠地测试数据库调用的结果。我知道由于模拟数据库调用,我将获得用户 ID“1”。
  3. 我们不需要引导我们的应用程序,也不需要提供任何配置或数据库来进行测试。

我们还可以做得更好。这就是它变得有趣的地方。


接口

为了进一步改进这一点,我们可以定义并实现一个接口。考虑以下代码。

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);
    }

}

这里发生了一些事情。

  1. 首先,我们为用户数据源定义一个接口。这定义了 addUser() 方法。
  2. 接下来,我们实现该接口。在本例中,我们创建一个 MySQL 实现。我们接受一个数据库连接对象,并使用它从数据库中获取用户。
  3. 最后,我们在 User 模型中强制使用实现 UserInterface 的类。这样可以保证数据源始终有一个可用的 getUser() 方法,无论使用哪个数据源来实现 UserInterface

请注意,我们的 User 对象类型提示 UserInterface 在其构造函数中。这意味着实现 UserInterface 的类必须传递到 User 对象中。这是我们所依赖的保证 - 我们需要 getUser 方法始终可用。

这样做的结果是什么?

  • 我们的代码现在完全可测试。对于User类,我们可以轻松地模拟数据源。 (测试数据源的实现将是单独的单元测试的工作)。
  • 我们的代码更加易于维护。我们可以切换不同的数据源,而无需更改整个应用程序的代码。
  • 我们可以创建任何数据源。 ArrayUser、MongoDbUser、CouchDbUser、MemoryUser 等
  • 如果需要,我们可以轻松地将任何数据源传递到我们的 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 模型的创建移至应用程序配置中的一个位置。结果是:

  1. 我们的代码保持干燥。 User 对象和选择的数据存储在我们应用程序的一个位置定义。
  2. 我们可以将 User 模型从使用 MySQL 切换到 ONE 位置中的任何其他数据源。这更易于维护。

最终想法

在本教程的过程中,我们完成了以下任务:

  1. 保持我们的代码干燥且可重用
  2. 创建了可维护的代码 - 如果需要,我们可以在整个应用程序的一个位置切换对象的数据源
  3. 使我们的代码可测试 - 我们可以轻松模拟对象,而无需依赖引导我们的应用程序或创建测试数据库
  4. 了解如何使用依赖注入和接口来创建可测试和可维护的代码
  5. 了解容器如何帮助我们的应用程序更易于维护

我相信您已经注意到,我们以可维护性和可测试性的名义添加了更多代码。可以对这种实现提出强有力的论据:我们正在增加复杂性。事实上,这需要项目的主要作者和合作者对代码有更深入的了解。

但是,技术债务总体减少远远超过了解释和理解的成本。

  • 代码的可维护性大大提高,可以在一个位置而不是多个位置进行更改。
  • 能够(快速)进行单元测试将大幅减少代码中的错误 - 特别是在长期或社区驱动的(开源)项目中。
  • 提前做额外的工作节省时间并减少以后的麻烦。

资源

您可以使用 Composer 轻松地将 MockeryPHPUnit 包含到您的应用程序中。将这些添加到 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 的更多信息。

  • 嘲笑:更好的方法
  • 使用 Composer 轻松进行包管理
  • 测试驱动的 PHP

对于 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn