laraval

laraval 建立你自己的模块:

模块目录

demo---模块名称
demo/DemoServiceProvider.php --模块入口service文件, 要放到config/app.php 配置中
class DemoServiceProvider extends ServiceProvider {

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    //初始化其他provider
    protected $providers = [
            \Collective\Html\HtmlServiceProvider::class
    ];

    //初始化别名
    protected $aliases = [
            "Sentry" => \Cartalyst\Sentry\Facades\Laravel\Sentry::class,
            "Image"  => \Intervention\Image\Facades\Image::class,
            'Form'   => \Collective\Html\FormFacade::class,
            'Html'   => \Collective\Html\HtmlFacade::class,
            'HTML'   => \Collective\Html\HtmlFacade::class
    ];

    /**
     * 项目启动运行
     *
     * @override
     * @return void
     */
    public function register()
    {
        $this->loadProvidersDependency();
        $this->registerAliases();
    }

    /**
     *所有的provider加载完成之后运行
     */
    public function boot()
    {
        初始化自己要加载的类
        $this->bindClasses();

        // setup views path
        // 初始化自己要加载的模板路径,第一个参数可以任意填写,可以为demo...
        $this->loadViewsFrom(__DIR__ . '/../../resources/views', 'demo');
        // include view composers 初始化自己的composer
        require __DIR__ . "/composers.php";

        // 自己的路由包 默认为http下routes,如果需要可以填写为demo下的routes,但是路径命名空间记得填写正确
        //Route::group(['middleware' => ['demo'], 
        //           'namespace' => 'Demo\Controllers']
        require __DIR__ . '/../Http/routes.php';
        //自定义运行命令
        require __DIR__ . '/bootstrap.php';

        //注册php artisan命令
        $this->registerCommands();

        $this->setupPublishDataCommand();

    }



    protected function bindClasses()
    {
        $this->app->bind('authenticator', function ()
        {
            return new SentryAuthenticator;
        });

        $this->app->bind('demo_helper', function ($app)
        {
            return new FileRouteHelper();
        });
    }

    protected function loadProvidersDependency()
    {
        foreach($this->providers as $provider)
        {
            $this->app->register($provider);
        }
    }

    protected function registerAliases()
    {
        foreach($this->aliases as $alias => $original)
        {
            AliasLoader::getInstance()->alias($alias, $original);
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     * @override
     */
    public function provides()
    {
        return $this->providers;
    }

    private function registerInstallCommand()
    {
        $this->app['demo.install'] = $this->app->share(function ($app)
        {
            return new InstallCommand;
        });

        $this->commands('demo.install');
    }

    private function registerCommands()
    {
        $this->registerInstallCommand();
    }



    protected function useMiddlewareCustomConfig()
    {
        App::instance('config', new ConfigMiddleware());

        Config::swap(new ConfigMiddleware());
    }


    protected function setupPublishDataCommand()
    {
        $this->publishAssets();
        $this->publishConfig();
        $this->publishViews();
        $this->publishMigrations();
    }

    protected function publishAssets()
    {
        $this->publishes([
                                 __DIR__ . '/../../public/packages/demo' => public_path('packages/demo'),
                         ]);

    }

    //发布配置,运行程序后会把demo下config/demo.php 复制发布到项目config下
    protected function publishConfig()
    {
        $this->publishes([
                                 __DIR__ . '/../../config/demo.php'        => config_path('demo.php')
                         ]);
    }

    protected function publishViews()
    {

        $this->publishes([
                                 __DIR__ . '/../../resources/views' => base_path('resources/views/vendor/demo'),
                         ]);
    }


    protected function publishMigrations()
    {

        $this->publishes([
                                 __DIR__ . '/../../database/migrations' => $this->app->databasePath() . '/migrations',
                         ]);
    }

laravel + phpunit

普通的test

基础测试集
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__ . '/../bootstrap/app.php';
        return $app;
    }

    //每次运行test的时候会运行
    public function refreshApplication()
    {
        if (empty($this->app) && !defined('Demo')) {
            $this->app = $this->createApplication();
        } else {
            $this->app = app();
        }
    }
}
真正测试类
class RestfulTest extends TestCase
{
    protected $app;


    /**
     * Clean up the testing environment before the next test.
     *
     * @return void
     */
    public function tearDown()
    {

    }

    /**
     * test
     */
    public function testDemo()
    {
        $res = null;
        try {
            if (1) {
                // 构建请求uri
                $uri = 'demo';

                //post参数
                $_POST = $postData = '{"test":"test"}';

                // get参数
                $get = ['test' => 'test'];
                $get = $_GET = $get;
                //请求uri
                $uri = sprintf($uri . '?%s', http_build_query($get));
                //这里只运行一次request,uri请求,如果要在一个test里面运行多次需要在构建request对象前清楚缓存
                // 清楚门面中的request对象,多次创建request请求的时候需要,防止request对象获取的值不变
                \Illuminate\Support\Facades\Facade::clearResolvedInstance('request');
                */
                // 创建request对象
                $request = \Illuminate\Http\Request::create(
                    $uri, 'post', [], [], [], [], $postData
                );

                //运行请求
                ob_start();
                $kernel = $this->app->make(Illuminate\Contracts\Http\Kernel::class);
                $response = $kernel->handle(
                    $request
                );
                $response->send();
                $kernel->terminate($request, $response);
                $res = ob_get_contents();
                ob_end_clean();

                //运行请求还有另外一种更简单的方式,但是这种方式需要symfony插件,并且在lumen下运行状况很多所以没有采用
                /*$this->call('post', $uri,  $postData);
                $this->clearInputs()->followRedirects()->assertPageLoaded($uri);
                $res = $this->response->getContent();*/
            } else {
                return false;
            }
        } catch (\Exception $e) {
            //dd($e->getMessage());
            return false;
        }

        $res = json_decode($res, true);
        if (isset($res['result']) && !empty($res['result'])) {
            $this->assertTrue(true);
        } else {
            $this->assertTrue($res);
        }

    }

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"---入口启动文件
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory suffix="Test.php">./tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
            <exclude>
                <file>./app/Http/routes.php</file>
            </exclude>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="test"/>这里代表config的配置文件的后缀,.env.test,如果要改成.env这里要留空
        <env name="CACHE_DRIVER" value="array"/>跟.env中的配置参数一样的含义,如果.env中已经配置可以去掉,如果配置了会覆盖.env中的配置
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值