Make your own contribution to the open source world of the world by writing a Laravel extension from scratch and publishing it to Packagist

Create a basic directory and structure

  • Create a Laravel project
  • Create a directory packages at the root of the project to store the extension packages for the tests
├── trash ├─ SRCCopy the code
  • Create the Commands directory to generate the console command
  • Create the Controllers directory to store the Controllers
  • Create a config directory to store configuration files
  • Create the Routes directory to hold our routes
  • Create swagger- UI directory to hold static pages for Swagger
  • Create a View directory to hold the interface that displays the UI

Introducing the swagger – the UI

From swagger website file download dependence, will under the disk file copy to packages/hanyun/swagger/SRC/swagger – below the UI/dist

│ ├ ─ ─ swagger - UI │ │ └ ─ ─ dist │ │ ├ ─ ─ the favicon. - 16 x16 PNG │ │ ├ ─ ─ the favicon - 32 x32. PNG │ │ ├ ─ ─ index. The HTML │ │ ├ ─ ─ Oauth2 - redirect. HTML │ │ ├ ─ ─ swagger - UI - bundle. Js │ │ ├ ─ ─ swagger - UI - bundle. Js. Map │ │ ├ ─ ─ swagger - UI - es - bundle - core. Js │ │ ├ ─ ─ swagger - UI - es - bundle - core. Js. Map │ │ ├ ─ ─ swagger - UI - es - bundle. Js │ │ ├ ─ ─ swagger - UI - es - bundle. Js. Map │ │ ├ ─ ─ Swagger - UI - standalone - preset. Js │ │ ├ ─ ─ swagger - UI - standalone - preset. Js. Map │ │ ├ ─ ─ swagger - UI. CSS │ │ ├ ─ ─ │ ├─ ├─ ├─ ├─ unteach.txt, ├─ unteach.txt, unteach.txt, unteach.txt, unteach.txtCopy the code

Create swagger profile,

File location/packages/hanyun/swagger/SRC/config/swagger. PHP

<? php /** * User=> Only * Time=> 16=>30 */ return [ "info" => [ "title" => "laravel swagger", "description" => 'laravel swagger generate OpenApi', "termsOfService" => "http://swagger.io/terms/", "Contact" = > [" email "= >" 1355081829 @qq.com "], "license" = > [" name "= >" MIT ", "url" = > ""]," version "= >" 1.0.0]," "servers" => [ [ "url" => "/", "description" => "laravel swagger OpenApi host" ] ], ];Copy the code

Create a view

File location packages/hanyun/swagger/SRC/view/index. The blade. The document on the PHP later released to laravel view under the directory

<! -- HTML for static distribution bundle build --> <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Swagger UI</title> <link rel="stylesheet" type="text/css" href="{{asset('swagger-ui/swagger-ui.css')}}" > <link rel="icon" type="image/png" href="{{asset('swagger-ui/favicon-32x32.png')}}" sizes="32x32" /> <link rel="icon" type="image/png" href="{{asset('swagger-ui/favicon-16x16.png')}}" sizes="16x16" /> <style> html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } *, *:before, *:after { box-sizing: inherit; } body { margin:0; background: #fafafa; } </style> </head> <body> <div id="swagger-ui"></div> <script src="{{asset('swagger-ui/swagger-ui-bundle.js')}}" charset="UTF-8"> </script> <script src="{{asset('swagger-ui/swagger-ui-standalone-preset.js')}}" charset="UTF-8"> </script> <script> window.onload = function() { // Begin Swagger UI call region const ui = SwaggerUIBundle({ url: "{{asset('swagger-ui/swagger.json')}}", dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }) // End Swagger UI call region window.ui = ui } </script> </body> </html>Copy the code

Create a controller to display the document interface

File location packages/hanyun/swagger/SRC/Controllers/SwaggerController. PHP



      

namespace Hanyun\Swagger\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SwaggerController extends Controller
{

    //
    public function index()
    {
        return view('swagger-ui.index'); }}Copy the code

Create routing

File location packages/hanyun/swagger/SRC/routes/swagger. PHP



      
/** * User: Only * Time: 17:04 */

use Illuminate\Support\Facades\Route;

Route::get('/swagger', [\Hanyun\Swagger\Controllers\SwaggerController::class, 'index']);


Copy the code

The create console command is used to generate documents

File location packages/hanyun/swagger/SRC/Commands/swagger. PHP



      

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Swagger extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swagger:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate swagger API';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $openapi = \OpenApi\scan(app_path() . '/Http/Controllers');
        header('Content-Type: application/json');
        $json = $openapi->toJson();
        $json = preg_replace('/\s{0,}\*\s{0,}#\s{0,}/'.The '#'.$json);
        $json = preg_replace('/\s{0,}\\\\r\\\\n\s{0,}/'.'\n'.$json);
        $json = preg_replace('/\s{0,}\*\s{0,}/'.' '.$json);
        $arr = json_decode($json.true);
        $arr['info'] = config('swagger.info');
        $arr['servers'] = config('swagger.servers');
        $json = json_encode($arr);
        file_put_contents(public_path('swagger-ui/swagger.json'), $json);
        return 0; }}Copy the code

To create a facade

File location packages/hanyun/swagger/SRC/Facades/swagger. PHP



      
/** * User: Only * Time: 16:39 */

namespace Hanyun\Swagger\Facades;

use Illuminate\Support\Facades\Facade;

class Swagger extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'swagger'; }}Copy the code

Create a provider to publish the extension

File location packages/hanyun/swagger/SRC/SwaggerProvider. PHP



      

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Swagger extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swagger:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate swagger API';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $openapi = \OpenApi\scan(app_path() . '/Http/Controllers');
        header('Content-Type: application/json');
        $json = $openapi->toJson();
        $json = preg_replace('/\s{0,}\*\s{0,}#\s{0,}/'.The '#'.$json);
        $json = preg_replace('/\s{0,}\\\\r\\\\n\s{0,}/'.'\n'.$json);
        $json = preg_replace('/\s{0,}\*\s{0,}/'.' '.$json);
        $arr = json_decode($json.true);
        $arr['info'] = config('swagger.info');
        $arr['servers'] = config('swagger.servers');
        $json = json_encode($arr);
        file_put_contents(public_path('swagger-ui/swagger.json'), $json);
        return 0; }}Copy the code

Modify the composer. Json below the extension package we created


{
    "name": "hanyun/swagger"."description": "Swagger for laravel"."keywords": [
        "swagger"."laravel"."openapi"]."license": "MIT"."authors": [{"name": "hanyun"."email": "[email protected]"}]."autoload": {
        "psr-4": {
            "Hanyun\\Swagger\\": "src/"}},"require": {
        "php": "^ 7.3"."zircote/swagger-php": "^ 3.1"}}Copy the code

Modify the composer. Json under the Laravel project we created

“Hanyun\\Swagger\\”: “Packages/hanyun/swagger/SRC” let our project can introduce our expansion pack, do the test, we can put our expansion pack after test pass issued to making it, and then published to the packagist.org, This way others can import your extensions in Composer

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Hanyun\\Swagger\\": "packages/hanyun/swagger/src",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    }

Copy the code

The final directory result is as follows:

Packages ├ ─ ─ hanyun │ └ ─ ─ swagger │ └ ─ ─ the SRC │ ├ ─ ─ Commands │ │ └ ─ ─ swagger. PHP │ ├ ─ ─ Controllers │ │ └ ─ ─ SwaggerController. PHP │ ├ ─ ─ Facades │ │ └ ─ ─ Swagger. PHP │ ├ ─ ─ Swagger. PHP │ ├ ─ ─ SwaggerProvider. PHP │ ├ ─ ─ the config │ │ └ ─ ─ Swagger. PHP │ ├ ─ ─ routes │ │ └ ─ ─ swagger. PHP │ ├ ─ ─ swagger - UI │ │ └ ─ ─ dist │ │ ├ ─ ─ the favicon - 16 x16. PNG │ │ ├ ─ ─ Favicon-32x32.png │ ├─ Index.html │ │ ├─ Heavy Metal Guitar school - - - - - - - - - - - - - - - - - - - - - - - - Swagger - UI - bundle. Js. Map │ │ ├ ─ ─ swagger - UI - es - bundle - core. Js │ │ ├ ─ ─ swagger - UI - es - bundle - core. Js. Map │ │ ├ ─ ─ │ ├── ├─ Standalone - Presets. Js │ │ ├── Standalone - Presets. Js │ │ ├── Presets Swagger - UI - standalone - preset. Js. Map │ │ ├ ─ ─ swagger - UI. CSS │ │ ├ ─ ─ swagger - UI. CSS. The map │ │ ├ ─ ─ swagger - UI. Js │ │ └ ─ ─ │ ├ ─ ├ ─ sci-1.txtCopy the code

test

\Hanyun\Swagger\SwaggerProvider::class /config/app. PHP providers :: Hanyun\Swagger\SwaggerProvider::class

Providers => [//... Hanyun\Swagger\SwaggerProvider::class], ' 'providers' => [//Copy the code

Hanyun\Swagger\Facades\ swagger ::class => Hanyun\ swagger \Facades\ swagger ::class => Hanyun\ swagger \Facades\ swagger ::class

'aliases' => [//... other omit 'swagger'=> Hanyun\Swagger\Facades\ swagger ::class], 'aliases' => [//... other omit 'swagger'=> Hanyun\Swagger\Facades\ swagger ::class]Copy the code

3. Run PHP Artisan Vendor :publish in the root directory of the project, find [4] Provider: Hanyun\Swagger\SwaggerProvider, enter the preceding number, and press Enter

PHP artian make:controller Api/v1/IndexController



      

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use OpenApi\Annotations as OA;

class IndexController extends Controller
{
    //
    / * * *@OA\Get(
     *     path="/api/index",
     *   security={{
     *     "api_key":{}
     *   }},
     *     @OA\ Response (Response = "200", the description = "* | | parameters shows that the note | | | | | | * : - : | : - : | : - : | -- - | -- - | -- - | * | status | | state [' cancelled ', Orders' waiting for payment ', 'success', 'payment'] take array index | | | | * ") * / *)
    public function index(Request $request)
    {
        return $request->all(); }}Copy the code

Modify App\Http\Controllers\ controller.php as follows



      

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use OpenApi\Annotations as OA;


/ * * *@OA\OpenApi(
 *     @OA\Info(* version="1.0.0", * title="Swagger Petstore", * description="This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", * termsOfService="http://swagger.io/terms/", *@OA\Contact(
 *             email="apiteam@swagger.io"
 *         ),
 *         @OA\ License (* name = "Apache 2.0," * url = "http://www.apache.org/licenses/LICENSE-2.0.html" *) *), *@OA\Server(
 *         description="OpenApi host",
 *         url="https://petstore.swagger.io/v3"
 *     ),
 *     @OA\ExternalDocumentation(
 *         description="Find out more about Swagger",
 *         url="http://swagger.io"
 *     )
 * )
 * @OA\SecurityScheme(
 *   securityScheme="api_key",
 *   type="apiKey",
 *   in="header",
 *   name="Authorization"
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests.DispatchesJobs.ValidatesRequests;
}

Copy the code

Config /swagger. PHP this automatically overwrites the default swagger configuration

6. Run PHP artisan Swagger :generate API in the project root directory

7. In the project root directory, run PHP artisan serve and open the project document

Release our extension pack

1. Submit to GitHub

2. Post to ackagist.org

Open theackagist.orgEnter the GitHub address of your extension and click Check to generate the extension

Specific Swagger documentation, Zircote/Swagger-PHP documentation

Welcome to Star and Fork at Github