Yii2 UrlManager: The Ultimate REST API Routing Solution
Pluralization, Patterns & More: Yii2 Routing Secrets

Yii2 URL Management: Configuring REST API Endpoints

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



Basic URL Manager Configuration

With resource and controller classes ready, you can access the resources using the URL like http://localhost/index.php?r=user/create, similar to what you can do with normal Web applications.

In practice, you usually want to enable pretty URLs and take advantage of HTTP verbs. For example, a request POST /users would mean accessing the user/create action. This can be done easily by configuring the urlManager application component in the application configuration like the following:

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
        ],
    ]

RESTful URL Rules in Action

Compared to the URL management for Web applications, the main new thing above is the use of [[yii\rest\UrlRule]] for routing RESTful API requests. This special URL rule class will create a whole set of child URL rules to support routing and URL creation for the specified controller(s). For example, the above code is roughly equivalent to the following rules:

[
        'PUT,PATCH users/<id>' => 'user/update',
        'DELETE users/<id>' => 'user/delete',
        'GET,HEAD users/<id>' => 'user/view',
        'POST users' => 'user/create',
        'GET,HEAD users' => 'user/index',
        'users/<id>' => 'user/options',
        'users' => 'user/options',
    ]

And the following API endpoints are supported by this rule:

  • GET /users: list all users page by page;
  • HEAD /users: show the overview information of user listing;
  • POST /users: create a new user;
  • GET /users/123: return the details of the user 123;
  • HEAD /users/123: show the overview information of user 123;
  • PATCH /users/123 and PUT /users/123: update the user 123;
  • DELETE /users/123: delete the user 123;
  • OPTIONS /users: show the supported verbs regarding endpoint /users;
  • OPTIONS /users/123: show the supported verbs regarding endpoint /users/123.

Customizing Routing Behavior

You may configure the only and except options to explicitly list which actions to support or which actions should be disabled, respectively. For example,

[
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'except' => ['delete', 'create', 'update'],
    ],

You may also configure patterns or extraPatterns to redefine existing patterns or add new patterns supported by this rule. For example, to support a new action search by the endpoint GET /users/search, configure the extraPatterns option as follows,

[
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'extraPatterns' => [
            'GET search' => 'search',
        ],
    ]

You may have noticed that the controller ID user appears in plural form as users in the endpoint URLs. This is because [[yii\rest\UrlRule]] automatically pluralizes controller IDs when creating child URL rules. You may disable this behavior by setting [[yii\rest\UrlRule::pluralize]] to be false.

Info: The pluralization of controller IDs is done by [[yii\helpers\Inflector::pluralize()]]. The method respects special pluralization rules. For example, the word box will be pluralized as boxes instead of boxs.

In case when the automatic pluralization does not meet your requirement, you may also configure the [[yii\rest\UrlRule::controller]] property to explicitly specify how to map a name used in endpoint URLs to a controller ID. For example, the following code maps the name u to the controller ID user.

[
        'class' => 'yii\rest\UrlRule',
        'controller' => ['u' => 'user'],
    ]

Extra Configuration for Contained Rules

It could be useful to specify extra configuration that is applied to each rule contained within [[yii\rest\UrlRule]]. A good example would be specifying defaults for expand parameter:

[
        'class' => 'yii\rest\UrlRule',
        'controller' => ['user'],
        'ruleConfig' => [
            'class' => 'yii\web\UrlRule',
            'defaults' => [
                'expand' => 'profile',
            ]
        ],
    ]

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu