The Yaf testable skeleton and composer supported.

Overview

Yaf skeleton

The Yaf testable skeleton and composer supported.

Sponsor me

Requirement

  • PHP >= 7.0
  • Yaf >= 3.0

Installation

  1. Update yaf.ini:
[yaf]
yaf.use_namespace=1
yaf.use_spl_autoload=1
...
  1. Create project.
$ composer create-project overtrue/yaf-skeleton myapp -vvv
  1. Web server rewrite rules:

    Apache

    #.htaccess
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* index.php
    

    Nginx

    server {
      listen 80;
      server_name  myapp.com;
      root   /path/to/myapp;
      index  index.php index.html index.htm;
    
      if (!-e $request_filename) {
        rewrite ^/(.*)  /index.php/$1 last;
      }
    }
    

    Lighttpd

    "/index.php/$1", ) }">
    $HTTP["host"] =~ "(www.)?myapp.com$" {
      url.rewrite = (
         "^/(.+)/?$"  => "/index.php/$1",
      )
    }
    

Application structor

├── .scripts
│   ├── .gitkeep
│   ├── common.sh
│   ├── job_phpcs.sh
│   ├── job_phpmd.sh
│   ├── job_phpunit.sh
│   ├── sami.phar
│   └── sami.php
├── app
│   ├── commands                # sora commands (namespace:\App\Commands)
│   ├── controllers             # Yaf Controllers (namespace:\)
│   ├── exceptions              # Exceptions (namespace:\App\Exceptions)
│   ├── facades                 # Service Facades (namespace:\)
│   ├── plugins                 # Yaf plugins (namespace:\)
│   ├── presenters              # Object presenters (namespace:\App\Presenters)
│   ├── services                # Services, the 3rd service bridges (namespace:\App\Services)
│   ├── traits                  # Traits (namespace:\App\Traits)
│   ├── views                   # Template files
│   ├── helpers.php             # Herlpers
│   ├── Bootstrap.php           # Yaf Bootstrap file
├── config
│   ├── application.ini     # Yaf config file
├── public                  # web extrence
│   └── index.php
├── sora                    # The command line tool
├── tests                   # Unit tests
└── vendor                  #
├── phpunit.xml.dist        # PHPUnit config file
├── .gitignore
├── .php_cs                 # PHP-CS-Fixer config file
├── composer.json
├── composer.lock
├── README.md

Controllers

$ ./sora make:controller Foo_Bar # or:foo_bar/FooBar/FooBarController
#
# /www/myapp/app/controllers/Foo/Bar.php Created!
# /www/myapp/tests/controllers/Foo/BarTest.php Created!

All controllers are created in the app/controllers directory,and test files are also created in the tests/controllers directorty.

Of course, you can also create tests independently:

$ ./sora make:test Foo_Bar # Also supports multiple type controller names
# /www/myapp/tests/controllers/Foo/BarTest.php Created!

The handle() method

The controller entry method handle():




class ExampleController extends BaseController
{
    public function handle()
    {
        return 'Hello world!';
        // return json(['foo' => 'bar']);
        // return redirect('https://easywechat.com');
        // return view('welcome', ['name' => 'MyApp']); // template engine require.
    }
}

Views

There is no built-in template engine. If you need to use a PHP template, we recommend that you use Plates, Plates is a native PHP template system that's fast, easy to use and easy to extend.

$ composer require league/plates -vvv

You can use view(string $template, array $data) helper in controller handle method as a result.

for example:

    public function handle()
    {
        $data = [
            'name' => 'overtrue',
            'age' => 28,
        ];

        return view('profile-page', $data);
    }


<h1><?= $name ?>h1>
<p><?= $age ?>p>

More usage please read the Plates Docs.

Unit tests

The difficulty of writing unit tests is inversely proportional to the quality of your code. The higher the code quality, the lower the difficulty of unit testing, so design your code well.

The unit test for creating the controller can be done with the following command:

$ ./sora make:test Foo_BarController

Write test cases

To create a controller test object, use,you can use the mock_controller function:

$controller = mock_controller(Foo_BarController::class);

// Indicates the method to mock, and the protected method is also mockable
$controller = mock_controller(Foo_BarController::class, ['getUsers', 'getApp']);

Assertion

We have such a controller:

    ...
    public function handle()
    {
        $params = Request::only('uids', 'screen_name', 'trim_status', 'has_extend', 'simplify', 'is_encoded');

        $users = $this->get('main.users.show_batch', $params);

        return $users;
    }
    ...

So the test should cover the above three behaviors:

public function testHandle()
{
    $input = [
        'uids' => '2193182644',
        'screen_name' => '安正超',
        'trim_status' => 0,
        'has_extend' => 1,
        'simplify' => 0,
        'is_encoded' => 0,
        'foo' => 'bar',
    ];

    Request::shouldReceive('only')
            ->with('uids', 'screen_name', 'trim_status', 'has_extend', 'simplify', 'is_encoded')
            ->andReturn($input);

    $controller = mock_controller(Users_Show_BatchController::class, ['get']); // mock the `get` method

    $controller->shouldReceive('get')->with('main.users.show_batch', array_except($_GET, ['foo']))
                                    ->andReturn('foo')
                                    ->once();

    $response = $controller->handle();

    $this->assertSame('foo', $response);
}

Facade Assertion

Request::shouldReceive('get')->with('mid')->andReturn('mock-mid')->once();
Log::shouldReceive('action')->with(48, 'oid', 'ext')->once();
..

Built-in auxiliary assertion methods

$this->shouldAbort($message, $code);

They are used to correspond to exceptions thrown by abort($message, $code); in the controller

Some helper methods in test case classes

Mock request method:

$this->method('post');

Mock request uri

$this->uri('/foo/bar?uid=12345');

Mock config:

$this->config('foo', 'bar');

Mock request IP:

$this->ip('127.0.0.1');

Mock $_SERVER vars:

$this->server('REQUEST_URI', '/foo/bar');

Docs

❤️ Sponsor me

Sponsor me

如果你喜欢我的项目并想支持它,点击这里 ❤️

Project supported by JetBrains

Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.

PHP 扩展包开发

想知道如何从零开始构建 PHP 扩展包?

请关注我的实战课程,我会在此课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

License

MIT

You might also like...
Easy to use, fast extendable small PHP Framework, like the one you ever missed. The skeleton-APP

About Tufu-Framework Easy to use, fast extendable PHP Framework, like the one you ever missed. Features included such as: Twig and extensions. Fast ro

A skeleton repository for Spatie's PHP Packages

:package_description This package can be used as to scaffold a framework agnostic package. Follow these steps to get started: Press the "Use template"

Basic PHP app with Composer used in Microsoft Docs examples

page_type languages products description urlFragment sample php azure This sample demonstrates a tiny PHP app with Composer. php-basic-composer PHP sm

A easy way to install your basic yii projetc, we have encrypt database password in phpfile, my class with alot funtions to help you encrypt and decrypt and our swoole server install just run ./yii swoole/start and be happy!

Yii 2 Basic Project Template with swoole and Modules Yii 2 Basic Project Template is a skeleton Yii 2 application best for rapidly creating small proj

Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily.
Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily.

Leaf is a PHP framework that helps you create clean, simple but powerful web apps and APIs quickly and easily. Leaf introduces a cleaner and much simpler structure to the PHP language while maintaining it's flexibility. With a simple structure and a shallow learning curve, it's an excellent way to rapidly build powerful and high performant web apps and APIs.

Symprowire is a PHP MVC Framework based and built on Symfony, using the ProcessWire CMS as DBAL and Service Provider.

Symprowire - PHP MVC Framework for ProcessWire 3.x Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Serv

FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Ruby on Rails.

FlyCubePHP FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Rub

Implementing programming best practices and patterns, and creating a custom PHP framework from scratch.

Implementing programming best practices and patterns, and creating a custom PHP framework from scratch.

An issue tracking tool based on hyperf+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.
An issue tracking tool based on hyperf+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.

介绍 本项目以 actionview 为蓝本,使用 Hyperf 框架进行重写。 本项目为 Hyperf 框架的 DEMO 项目 原 ActionView 介绍 English | 中文 一个类Jira的问题需求跟踪工具,前端基于reactjs+redux、后端基于php laravel-frame

Comments
  • Config::set($key, $value)方法没有实现

    Config::set($key, $value)方法没有实现

    file: app\helpers.php

    function config($property, $default = null)
        {
            if (is_array($property)) {
                list($key, $value) = $property;
                /**
                 *此处报错, Config 类没有实现该 set 方法
                 */
                return Config::set($key, $value);
            }
    
            return Config::get($property, $default);
        }
    
    opened by fusions836 4
  • 测试用例失败

    测试用例失败

    直接运行测试用例提示: image tests/Registry.php tests/Dispatcher.php 都是同样问题,将namespace由Yaf改成Yaf\Tests 解决此问题,在运行测试用例提示: image

    请指点下错在了哪里,为何运行测试用例不成功,或者能在README.md里增加基本测试通过的运行命令。

    opened by caojiabin2012 3
  • Bug及建议

    Bug及建议

    下面字符串转ASCII的方法找不到类...

    https://github.com/overtrue/yaf-skeleton/blob/bfb5624a1975caa5f50efa32d7c6e547b6c1c4de/app/support/Str.php#L48

    建议:

    1. 引入EloquentORM,帮助广大群众解决ORM问题
    2. 引入一个成熟Validator,解放广大群众于参数校验泥潭
    opened by zuoRambo 1
  • 执行 composer 提示 Cound not found

    执行 composer 提示 Cound not found

    composer create-project overtrue/yaf-skeleton myapp -vvv
    

    提示:

      [InvalidArgumentException]
      Could not find package overtrue/yaf-skeleton with stability stable.
    

    环境:

    • Mac
    • PHP 7.1.7 (cli)
    • compsoer 1.5.2

    全部输出信息:

    ~/playground » composer create-project overtrue/yaf-skeleton myapp -vvv      svenhe@hsw-MacBook-Pro
    Loading config file /Users/svenhe/.composer/config.json
    Loading config file /Users/svenhe/.composer/auth.json
    Reading /Users/svenhe/.composer/composer.json
    Loading config file /Users/svenhe/.composer/config.json
    Loading config file /Users/svenhe/.composer/auth.json
    Loading config file /Users/svenhe/.composer/composer.json
    Loading config file /Users/svenhe/.composer/auth.json
    Reading /Users/svenhe/.composer/auth.json
    Checked CA file /private/etc/ssl/cert.pem: valid
    Executing command (/Users/svenhe/.composer): git branch --no-color --no-abbrev -v
    Executing command (/Users/svenhe/.composer): git describe --exact-match --tags
    Executing command (/Users/svenhe/.composer): git log --pretty="%H" -n1 HEAD
    Executing command (/Users/svenhe/.composer): hg branch
    Executing command (/Users/svenhe/.composer): fossil branch list
    Executing command (/Users/svenhe/.composer): fossil tag list
    Executing command (/Users/svenhe/.composer): svn info --xml
    Reading /Users/svenhe/.composer/vendor/composer/installed.json
    Running 1.5.2 (2017-09-11 16:59:25) with PHP 7.1.7 on Darwin / 17.4.0
    Downloading https://packagist.phpcomposer.com/packages.json
    Writing /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/packages.json into cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2013.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2014.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2015.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2016.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2017.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2017-07.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2017-10.json from cache
    Downloading https://packagist.phpcomposer.com/p/provider-2018-01%24124a61132f578bd4d7a0789d71046463f35788fe0dc1d9a851afcb215d1d930c.json
    Writing /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2018-01.json into cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-2018-04.json from cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-archived.json from cache
    Downloading https://packagist.phpcomposer.com/p/provider-latest%24d431c7eab98b9242fec3e05b787209f91965e1b5f199c7193eeac7acedd758b9.json
    Writing /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/p-provider-latest.json into cache
    Reading /Users/svenhe/.composer/cache/repo/https---packagist.phpcomposer.com/provider-overtrue$yaf-skeleton.json from cache
    
    
      [InvalidArgumentException]
      Could not find package overtrue/yaf-skeleton with stability stable.
    
    
    Exception trace:
     () at phar:///usr/local/bin/composer/src/Composer/Command/CreateProjectCommand.php:310
     Composer\Command\CreateProjectCommand->installRootPackage() at phar:///usr/local/bin/composer/src/Composer/Command/CreateProjectCommand.php:157
     Composer\Command\CreateProjectCommand->installProject() at phar:///usr/local/bin/composer/src/Composer/Command/CreateProjectCommand.php:143
     Composer\Command\CreateProjectCommand->execute() at phar:///usr/local/bin/composer/vendor/symfony/console/Command/Command.php:266
     Symfony\Component\Console\Command\Command->run() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:861
     Symfony\Component\Console\Application->doRunCommand() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:208
     Symfony\Component\Console\Application->doRun() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:245
     Composer\Console\Application->doRun() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:127
     Symfony\Component\Console\Application->run() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:100
     Composer\Console\Application->run() at phar:///usr/local/bin/composer/bin/composer:54
     require() at /usr/local/bin/composer:24
    
    create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--repository REPOSITORY] [--repository-url REPOSITORY-URL] [--dev] [--no-dev] [--no-custom-installers] [--no-scripts] [--no-progress] [--no-secure-http] [--keep-vcs] [--no-install] [--ignore-platform-reqs] [--] [<package>] [<directory>] [<version>]
    
    opened by heshiweij 1
Releases(1.1.1)
Owner
安正超
Keep calm and coding.
安正超
Mako skeleton application.

Mako Framework Mako is a lightweight and easy to use PHP framework based on the MVC architectural design pattern. Check out the documentation and crea

Mako Framework 27 Nov 12, 2022
🎁 Datagrid component project skeleton based on Nette Framework

?? Datagrid component project skeleton based on Nette Framework

Contributte 4 Dec 14, 2022
Slim 3 skeleton working with Google App Engine include cron configuration.

Slim3 GAE Skeleton Slim 3 skeleton working with Google App Engine include cron configuration. Demo https://slim3-gae-skeleton.appspot.com/health_check

Jared Chu 2 May 10, 2018
A skeleton to get started with Silex

Silex Skeleton WARNING: Silex is in maintenance mode only. Ends of life is set to June 2018. Read more on Symfony's blog. Welcome to the Silex Skeleto

Silex 789 Dec 5, 2022
lumen ^6.0 skeleton

Lumen skeleton It can format code and check the error code when submit code. Use the best api response package of QeeZer/api-responder. Comprehensive

齐子 1 Apr 1, 2022
Slim Framework skeleton application with MVC Schema

Slim Framework skeleton application with MVC Schema

JingwenTian 9 Apr 29, 2021
Slim Framework 3 Skeleton Application + PagSeguro Lib

Slim Framework 3 Skeleton Application + PagSeguro Lib Aplicação simples para geração do Token para pagamentos no PagSeguro (método transparente) e env

Raí Siqueira 1 Feb 26, 2018
Slim 3 MVC Skeleton With Swoole

Slim 3 MVC Skeleton With Swoole ##Features Quickly setup and start working on a new Slim Framework 3 . Use the latest Slim 3 with the PHP-View templat

kcloze 53 Aug 17, 2022
MaxPHP HTTP project skeleton.

轻量 • 简单 • 快速 一款基于swoole的组件化的轻量PHP框架,可以用作API开发,方便快速。 主要特性 组件和框架核心分离 基于 Psr7 的 HTTP-Message 基于 Psr11 的容器 基于 Psr14 的事件 基于 Psr15 的中间件 基于 Psr16 的缓存组件,支持 Fi

chengyao 9 Dec 15, 2022
This publication describes a standard filesystem skeleton suitable for all PHP packages

pds/skeleton This publication describes a standard filesystem skeleton suitable for all PHP packages. Please see https://github.com/php-pds/skeleton_r

null 2k Dec 30, 2022