laraval

来源:互联网 发布:公司注册淘宝店铺流程 编辑:程序博客网 时间:2024/06/05 22:43

  • laraval 建立你自己的模块
    • 模块目录
  • laravel phpunit
    • 普通的test
    • phpunitxml

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>
原创粉丝点击