Code Monkey home page Code Monkey logo

yii2-rest-app's Introduction

Шаблон проекта RESTful API на Yii2


Этот шаблон RESTful API на Yii 2, основанный на шаблоне приложения advanced.

В шаблоне frontend оставлен практически без изменений, переделке подверглась backend часть, которая теперь заточена под rest api. Аутентификация пользователей делается с помощью JSON Web Token.


Требования

Системные требования те же, что и для basic или advanced приложения на Yii2


Установка

git clone https://github.com/Den2016/yii2-rest-app.git
cd yii2-rest-app
composer install
init или php init

далее настраиваем соединение с базой данных в /common/config/main-local.php далее

./yii migrate 1
./yii migrate --migrationPath=@yii/rbac/migrations
./yii migrate 

TODO много чего

пример файла .htaccess для OpenServer

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Создаем простейшую точку входа. Для этого в api/config/main.php в components->urlManager->rules добавляем еще один массив, то есть urlManager будет выглядеть так

        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => UrlRule::class,
                    'controller' => 'user',
                    'pluralize' => true,
                ],
                [
                    'class' => UrlRule::class,
                    'controller' => 'login',
                    'extraPatterns' => [
                        'POST signup' => 'signup',
                        'POST login' => 'login',
                        'GET logout' => 'logout',
                    ],
                    'pluralize' => false,
                ],
                //добавленный массив
                [
                    'class' => UrlRule::class,
                    'controller' => 'api',
                    'pluralize' => false,
                ],
            ],
        ],

далее в api/controllers создаем контроллер ApiController

<?php


namespace api\controllers;


use yii\rest\Controller;

class ApiController extends Controller
{
    public function actionIndex(){
        return [1,2,3,'test'];
    }
}

в результате при обращении к /api методом GET мы должны получить следующий JSON

{
    "success": true,
    "data": [
        1,
        2,
        3,
        "test"
    ],
    "statusCode": 200,
    "statusText": "OK"
}

форматирование ответа производится в api/config/main.php в обработчике on beforeSend

yii2-rest-app's People

Contributors

arogachev avatar bscheshirwork avatar cebe avatar creocoder avatar davertmik avatar den2016 avatar githubjeka avatar gonimar avatar jasrags avatar jwaldock avatar kartik-v avatar klimov-paul avatar maximal avatar mohorev avatar naktibalda avatar pana1990 avatar pastuhov avatar qiangxue avatar ragazzo avatar resurtm avatar rugabarbo avatar samdark avatar schmunk42 avatar sdkiller avatar silverfire avatar skiptirengu avatar slavcodev avatar softark avatar thiagotalma avatar trianman avatar

Forkers

sergolisitcyn

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.