php-deal/framework 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

php-deal/framework

Composer 安装命令:

composer require php-deal/framework

包简介

Design by Contract framework for PHP

README 文档

README

Design by Contract framework for PHP

What is Design by Contract?

The specification of a class or interface is the collection of non-private items provided as services to the caller, along with instructions for their use, as stated in phpDoc. Design By Contract is an effective technology for creating a specification.

The fundamental idea of Design By Contract is to treat the services offered by a class or interface as a contract between the class (or interface) and its caller. Here, the word "contract" is meant to convey a kind of formal, unambiguous agreement between two parties:

  • requirements upon the caller made by the class
  • promises made by the class to the caller

If the caller fulfills the requirements, then the class promises to deliver some well-defined service. Some changes to a specification/contract will break the caller, and some won't. For determining if a change will break a caller, C++ FAQs uses the memorable phrase "require no more, promise no less": if the new specification does not require more from the caller than before, and if it does not promise to deliver less than before, then the new specification is compatible with the old, and will not break the caller.

Build Status GitHub release Code Coverage Scrutinizer Code Quality Minimum PHP Version License

Installation

PhpDeal framework can be installed with composer. Installation is quite easy, just ask composer to download the framework with its dependencies by running the command:

$ composer require php-deal/framework

Setup

Put the following code at the beginning of your application entry point or require it from an external file.

$instance = ContractApplication::getInstance();
$instance->init(array(
    'debug'    => true,
    'appDir'   => __DIR__,
    'excludePaths' => [
        __DIR__ . '/vendor'
    ],
    'includePaths' => [

    ],
    'cacheDir' => __DIR__.'/cache/',
));

Symfony setup

Put the following code in app_dev.php and adapt it to match your folder structure. The appDir must point to the folder containing the src files, not the document root folder !

$instance = ContractApplication::getInstance();
$instance->init(array(
    'debug'    => true,
    'appDir'   => __DIR__ . '/../src',
    'excludePaths' => [

    ],
    'includePaths' => [

    ],
    'cacheDir' => __DIR__.'/var/cache/',
));

Pre and Post Contracts

The pre contracts specify the preconditions (requirements) before a statement is executed. The most typical use of this would be in validating the parameters to a function. The post contracts (promises) validate the result of the statement. The most typical use of this would be in validating the return value of a method and of any side effects it has. The syntax is:

<?php
namespace Vendor\Namespace;

use PhpDeal\Annotation as Contract; //import DbC annotations

/**
 * Some account class
 */
class Account
{

    /**
     * Current balance
     *
     * @var float
     */
    protected $balance = 0.0;

    /**
     * Deposits fixed amount of money to the account
     *
     * @param float $amount
     *
     * @Contract\Verify("$amount>0 && is_numeric($amount)")
     * @Contract\Ensure("$this->balance == $__old->balance+$amount")
     */
    public function deposit($amount)
    {
        $this->balance += $amount;
    }
}

By definition, if a pre contract fails, then the body received bad parameters. A ContractViolation exception is thrown. If a post contract fails, then there is a bug in the body. A ContractViolation exception is thrown.

Invariants

Invariants are used to specify characteristics of a class that always must be true (except while executing a protected or private member function).

The invariant is a contract saying that the asserts must hold true. The invariant is checked when a class constructor completes and at the end of the class public methods:

<?php
namespace Vendor\Namespace;

use PhpDeal\Annotation as Contract; //import DbC annotations

/**
 * Some account class
 *
 * @Contract\Invariant("$this->balance > 0")
 */
class Account
{

    /**
     * Current balance
     *
     * @var float
     */
    protected $balance = 0.0;

    /**
     * Deposits fixed amount of money to the account
     *
     * @param float $amount
     */
    public function deposit($amount)
    {
        $this->balance += $amount;
    }
}

Invariants contain assert expressions, and so when they fail, they throw a ContractViolation exception.

NOTE: The code in the invariant may not call any public non-static members of the class, either directly or indirectly. Doing so will result in a stack overflow, as the invariant will wind up being called in an infinitely recursive manner.

Contract propagation

There a some differences in inheritance of the contracts:

  1. Ensure
  • if provided Ensure will automatically inherit all contracts from parent class or interface
  1. Verify
  • if provided Verify will not inherit contracts from parent class or interface
  • to inherit contracts you will need to provide @inheritdoc or the Inherit contract
  1. Invariant
  • if provided Invariant will inherit all contracts from parent class or interface
  1. Inherit
  • if provided Inherit will inherit all contracts from the given level (class, method) without the need to provide a contract on your current class or method

Notes:

  • The parsing of a contract only happens IF you provide any given annotation from this package. Without it, your contracts won't work!
  • The annotation must not have curly braces ({}) otherwise the annotation reader can't find them.
class Foo extends FooParent
{
    /**
     * @param int $amount
     * @Contract\Verify("$amount != 1")
     */
    public function bar($amount)
    {
        ...
    }
}
    
class FooParent
{
    /**
     * @param int $amount
     * @Contract\Verify("$amount != 2")
     */
    public function bar($amount)
    {
        ...
    }
}
    

Foo::bar accepts 2 literal as a parameter and does not accept 1.

With @inheritdoc:

class Foo extends FooParent
{
    /**
     * @param int $amount
     * @Contract\Verify("$amount != 1")
     * {@inheritdoc}
     */
    public function bar($amount)
    {
        ...
    }
}
    
class FooParent
{
    /**
     * @param int $amount
     * @Contract\Verify("$amount != 2")
     */
    public function bar($amount)
    {
        ...
    }
}
    

Foo::bar does not accept 1 and 2 literals as a parameter.

For postconditions (Ensure and Invariants contracts) subclasses inherit contracts and they don't need @inheritdoc. Example:

    
/**
 * @Contract\Invariant("$this->amount != 1")
 */
class Foo extends FooParent
{
    
}

/**
 * @Contract\Invariant("$this->amount != 2")
 */
class FooParent
{
    /**
     * @var int
     */
    protected $amount;
    
    /**
     * @param int $amount
     */
    protected function setBar($amount)
    {
        $this->amount = $amount;
    }
}
    

Foo::setBar does not accept 1 and 2 literals as a parameter.

If you don't want to provide a contract on your curent method/class you can use the Inherit annotation:

class Foo extends FooParent
{
    /**
     * @param int $amount
     * @Contract\Inherit
     */
    public function bar($amount)
    {
        ...
    }
}
    
class FooParent
{
    /**
     * @param int $amount
     * @Contract\Verify("$amount != 2")
     */
    public function bar($amount)
    {
        ...
    }
}

Foo:bar() does accept eveything, except: 2

Integration with assertion library

To enhance capabilities of contracts, it's possible to use assertion library.

    /**
     * Deposits fixed amount of money to the account
     *
     * @param float $amount
     *
     * @Contract\Ensure("Assert\Assertion::integer($this->balance)")
     */
    public function deposit($amount)
    {
        $this->balance += $amount;
    }

More assertions

IDE Integration

To improve your productivity with PhpStorm, you should definitely install a Go! AOP Framework plugin (>=1.0.1) to have a PHP syntax highlighting for defining contracts and navigation to AOP advices. PhpStorm example

Common issues

Fatal error: Uncaught Error: Class 'Go\ParserReflection\Instrument\PathResolver'
Fatal error: Uncaught Error: Class 'Go\ParserReflection\Instrument\PathResolver' 
not found in .../vendor/goaop/parser-reflection/src/ReflectionEngine.php on line XXX

This happens if your appDir configuration points at the same level as your vendor directory. To solve this issue try adding your vendor folder into the excludePaths configuration.

ContractApplication::getInstance()->init(array(
    'debug'    => true,
    'appDir'   => __DIR__,,
    'excludePaths' => [
        __DIR__ . '/vendor'
    ],
    'cacheDir' => __DIR__.'/cache/',
));

php-deal/framework 适用场景与选型建议

php-deal/framework 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.94k 次下载、GitHub Stars 达 253, 最近一次更新时间为 2017 年 12 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 php-deal/framework 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 php-deal/framework 我们能提供哪些服务?
定制开发 / 二次开发

基于 php-deal/framework 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 5.94k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 253
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 253
  • Watchers: 14
  • Forks: 21
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-12-12