use Yii;
use yii\rest\Controller;
use yii\filters\auth\AuthInterface;
use yii\filters\Cors;
use yii\filters\ContentNegotiator;
use yii\filters\HTTPBearerAuth;
////use yii\filters\RateLimiter;
final class BehaviorController extends Controller
code
Assistant
User
Assistant
User
i want a complete baseApiController with comments explaining how to use it
Assistant
User
i want a comment for controllers using the baseApiController as extended and the benefits, keep it short and sweet
Assistant
Certainly! Here’s a concise comment you can add at the top of your controllers that extend BaseApiController:
php
/**
* Controller extending BaseApiController
*
* Benefits:
* - Inherits standardized CORS and JSON response settings
* - Centralized authentication handling with easy customization
* - Reduces repetitive code, promotes consistency across APIs
* - Simplifies maintenance by managing common behaviors in one place
*/
You can place this comment just above the class declaration in any controller that extends BaseApiController.
public function behaviors(): array
{
$behaviors = parent::behaviors();
//$behaviors['rateLimiter'] = [];
/**
* CORS Filter
* @url https://www.yiiframework.com/doc/api/2.0/yii-filters-cors
*
* Handles Cross-Origin Resource Sharing headers and preflight OPTIONS requests.
* This enables your API to accept requests from other domains (origins).
* Must be placed BEFORE authentication so preflight OPTIONS requests are NOT blocked.
*
* Note: CORS filter must be before the Authenticator behavior
*/
$behaviors['corsFilter'] =
[
'class' => Cors::class,
'cors' =>
[
/**
* Allowed domains/origins that can access your API.
* '*' allows all origins (not recommended for production).
*
* 'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
*/
//'Origin' => $this->getAllowedOrigins(),
'Origin' => ['http://localhost:1234'],
/**
* HTTP methods that browsers are allowed to use when accessing your API.
* Adjust this list according to your API specification.
*
* 'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
*/
'Access-Control-Request-Method' => ['GET', 'POST', 'OPTIONS'],
// CSRF validation is ON by default, for POST requests coming from form or AJAX
// To send CSRF token, Yii2 uses header 'X-CSRF-Token' or param '_csrf'
/**
* Allowed HTTP headers clients can use during the actual requests.
* This should include Authorization for bearer tokens and other headers you expect.
*
* Common headers your React app will send are:
*
* - Authorization (for Bearer token)
* - Your backend CORS must allow both 'Authorization' and 'Content-Type' in Access-Control-Allow-Headers.
* - Also, 'OPTIONS' requests must bypass authentication for CORS preflight
* (see 'except' => ['options'] in authenticator behavior).
* - Content-Type (usually application/json)
* - X-Requested-With (sometimes added by libraries)
* - X-CSRF-Token (if using CSRF protection, mostly for stateful apps)
* - Accept (To ask API which format it supports) Often handled automatically, usually no CORS action needed
*/
'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type', 'X-Requested-With', 'X-CSRF-Token'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,// 86400 - 24 hours
],
];
/**
* Content Negotiation
* @url https://www.yiiframework.com/doc/api/2.0/yii-filters-contentnegotiator
*
* Note: Content Negotiation needs to be after CORS filer to ensure responses are JSON
*/
$behaviors['contentNegotiator'] =
[
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
/**
* Authorization:
* React app must include this header *after* login/sign-up, for every
* authenticated request (fetch, axios).
*
* Example:
*
* fetch('https://api.yoursite.com/v1/account', {
* method: 'GET',
* headers: {
* 'Authorization': `Bearer ${token}`,// Bearer token for authentication
* 'Content-Type': 'application/json'
* }
* })
* .then(response => response.json())
* .then(data => {
* console.log('User profile:', data);
* }).catch(console.error);
*
* Note: Authentication filter comes after CORS filter and Content Negotiator
*/
$behaviors['authenticator'] =
[
'class' => JwtHttpBearerAuth::class,
'except' => ['options', 'login', 'signup'],// exclude OPTIONS explicitly here too
];
}
/**
* ENV and CORS Origins
* Fetch allowed origins from env variable
* Assume your .env has: ALLOWED_ORIGINS=https://example.com,http://localhost:3000
*/
protected function getAllowedOrigins(): array
{
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
// Split into array, trim whitespace, remove empties
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins))
{
// default origin for dev, adjust accordingly
$origins = ['http://localhost:1234'];
}
return $origins;
}
since majority of my controllers will be using the same cors and content negotiation, and with some minor differences in the acess-control... could I not
write a controller that is called as a extend, so than I dont need to add these to each?
Yes, absolutely! In Yii2, creating a base controller class with shared behaviors (like CORS, content negotiation, authentication, etc.) is a very common and recommended practice. This way, you avoid repeating the same behaviors in every controller, promote DRY (Don't Repeat Yourself) principles, and centralize behavior management.
How to implement a base controller class with common behaviors:
Create a BaseApiController (or any name you prefer) which extends yii\rest\Controller.
Put all common behaviors in this base controller's behaviors() method.
Extend this base controller in your actual API controllers.
Override behaviors or properties in child controllers only if necessary (e.g., add/remove allowed origins, customize authentication exceptions, etc).
Example Implementation
php
<?php
namespace app\controllers;
use Yii;
use yii\rest\Controller;
use yii\web\Response;
use yii\filters\Cors;
use yii\filters\ContentNegotiator;
class BaseApiController extends Controller
{
public function behaviors(): array
{
$behaviors = parent::behaviors();
// CORS Filter - placed before authenticator and content negotiation
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
// Content Negotiator - after CORS
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
// Authentication - example using HttpBearerAuth or JwtHttpBearerAuth
$behaviors['authenticator'] = [
'class' => \app\components\JwtHttpBearerAuth::class,
'except' => ['options', 'login', 'signup'], // customize exclusions if needed
];
return $behaviors;
}
/**
* Fetch allowed origins from env variable or fallback to default.
*/
protected function getAllowedOrigins(): array
{
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins)) {
return ['http://localhost:1234']; // default origin for development
}
return $origins;
}
}
Using this base controller in other controllers:
Now in your other REST controllers, just extend BaseApiController instead of yii\rest\Controller:
php
<?php
namespace app\controllers;
class UserController extends BaseApiController
{
// Additional behaviors or overrides if necessary
public function behaviors(): array
{
$behaviors = parent::behaviors();
// Example: if you want to add/remove allowed methods in CORS for this controller
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
// Example: override auth exceptions
$behaviors['authenticator']['except'] = ['options', 'signup', 'reset-password'];
return $behaviors;
}
// Your actions here
}
Notes
Put your reusable logic for fetching allowed origins or other helpers in the base controller.
In complex projects, you can also separate CORS, Authenticator filters as behaviors or components and configure them per controller.
You must keep CORS filter before the authenticator to allow OPTIONS preflight requests to pass without authentication.
You can also configure rate limiting here if needed.
Make sure the namespace and imports are correct for your project.
Summary
Yes, create one base REST controller with common CORS / ContentNegotiator / Auth behaviors.
All your other REST controllers extend this base class.
Override or extend behaviors only when necessary.
This reduces code duplication and increases maintainability.
If you'd like, I can help create a fully detailed base controller example with some customizable parameters too. Just let me know!
Yes, exactly! That's a very good approach to make your base controller more generic and flexible.
Why leaving those values empty or minimal in the base controller and setting them in child controllers is a good idea:
Base controller acts as a common foundation; it provides the default structure and most common settings.
Some options like 'Access-Control-Request-Method' or 'authenticator''except' parameters often vary from controller to controller because different endpoints have different access rules.
By setting these to empty or minimal defaults in the base controller, you reduce unnecessary overrides.
Child controllers can then explicitly define only what differs from the base — this improves clarity and avoids accidental "inheritance" of undesired behaviors.
How to do this:
1. Make minimal or empty defaults in BaseApiController:
php
public function behaviors(): array
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
// Leave 'Access-Control-Request-Method' empty or with a minimal set
//'Access-Control-Request-Method' => [],
// You can even optionally leave it out entirely, which means allow all by default
'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
$behaviors['authenticator'] = [
'class' => \app\components\JwtHttpBearerAuth::class,
// empty or minimal except list (e.g., only 'options', which is usually universal)
'except' => ['options'],
];
return $behaviors;
}
2. Override in child controllers as needed:
php
public function behaviors(): array
{
$behaviors = parent::behaviors();
// set allowed HTTP methods for CORS preflight checks specific to this controller
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
// extend or replace excluded routes from authentication as needed
$behaviors['authenticator']['except'] = ['options', 'signup', 'reset-password'];
return $behaviors;
}
Additional tips:
If you want to add to the array inherited from base instead of replacing, you can merge arrays like this:
php
// Add extra HTTP methods to existing from base
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = array_merge(
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] ?? [],
['OPTIONS']
);
// Add extra except routes, maintaining base except list
$behaviors['authenticator']['except'] = array_merge(
$behaviors['authenticator']['except'] ?? [],
['signup', 'reset-password']
);
Carefully watch for duplicate entries after merging by applying array_unique() if needed.
Summary
Yes, you can—and, in many cases, should—keep those arrays empty or minimal in BaseApiController.
Set or override them specifically in each controller where requirements differ.
This is clean, flexible, and conforms to good design principles.
If you want, I can help you write a reusable trait or helper method to handle merging behaviors cleanly too!
Certainly! Below is a complete BaseApiController implementation with detailed comments explaining each part, showing how to centralize common behaviors (CORS, Content Negotiation, Authentication) and how to extend or override them in child controllers.
php
<?php
namespace app\controllers;
use Yii;
use yii\rest\Controller;
use yii\web\Response;
use yii\filters\Cors;
use yii\filters\ContentNegotiator;
/**
* Class BaseApiController
*
* This is a base REST API controller that provides common behaviors for:
* - CORS (Cross-Origin Resource Sharing)
* - Content Negotiation (usually JSON)
* - Authentication (using JWT Bearer token here as example)
*
* Most of your API controllers should extend this base controller
* to leverage centralized behavior definitions and avoid duplication.
*
* === Usage ===
*
* 1. Extend this controller in your API controllers:
* class UserController extends BaseApiController { ... }
*
* 2. Override behaviors() method in child controllers to customize CORS
* settings and authentication exceptions as needed (see examples below).
*
* 3. Optionally, configure your allowed CORS origins via environment variable
* CORS_ORIGINS as a comma-separated list, e.g.:
* CORS_ORIGINS=https://example.com,http://localhost:3000
* If not set, defaults to allowing only http://localhost:1234.
*
* 4. Ensure that your authentication component (e.g., JwtHttpBearerAuth) is properly set up.
*/
class BaseApiController extends Controller
{
/**
* Override behaviors() to add CORS, content negotiation, and authentication.
*
* @return array The behaviors for this controller.
*/
public function behaviors(): array
{
$behaviors = parent::behaviors();
// -------------------------------------------------------------------
// CORS Filter
// -------------------------------------------------------------------
// Note: This must be before the authenticator to allow OPTIONS preflight
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
// Allowed request origins - set via env variable or fallback default
'Origin' => $this->getAllowedOrigins(),
// Allowed HTTP methods in CORS preflight
// Can be overridden in child controllers to narrow methods per controller
// If left empty or not set here, 'Cors' defaults to all common HTTP verbs allowed.
// 'Access-Control-Request-Method' => ['GET', 'POST', 'OPTIONS'],
// Allowed request headers in CORS
'Access-Control-Allow-Headers' => [
'Authorization', // Needed for Bearer tokens
'Content-Type', // Often application/json
'X-Requested-With', // AJAX requests
'X-CSRF-Token', // If you use CSRF
],
// Allow credentials (cookies, HTTP auth, etc.) in requests
'Access-Control-Allow-Credentials' => true,
// Preflight OPTIONS request cache duration (seconds)
'Access-Control-Max-Age' => 3600,
],
];
// -------------------------------------------------------------------
// Content Negotiator
// -------------------------------------------------------------------
// Automatically respond with JSON response format
// Must come after CORS filter to ensure headers are sent correctly
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
// -------------------------------------------------------------------
// Authentication
// -------------------------------------------------------------------
// Use your own Auth class here. JwtHttpBearerAuth is just an example.
//
// The `except` field allows specific endpoints to skip authentication,
// e.g., OPTIONS (CORS preflight) and public endpoints like login/signup.
//
// Override this in child classes if necessary.
$behaviors['authenticator'] = [
'class' => \app\components\JwtHttpBearerAuth::class,
'except' => ['options'], // Typically always exclude OPTIONS
];
return $behaviors;
}
/**
* Get allowed origins for CORS from environment variables.
*
* Reads the 'CORS_ORIGINS' env var which should be a comma-separated list, e.g.:
* https://example.com,http://localhost:3000
*
* @return string[] List of allowed origins for CORS.
*/
protected function getAllowedOrigins(): array
{
// Get from env or fallback to empty string
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
// Split by comma, trim whitespace, remove empty entries
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
// If nothing provided, default to localhost dev environment
if (empty($origins)) {
return ['http://localhost:1234'];
}
return $origins;
}
}
How to Override and Customize in Child Controllers
php
<?php
namespace app\controllers;
/**
* Example User API controller extending BaseApiController.
*
* Here we override or extend default behaviors to:
* - Limit CORS allowed methods to GET, POST, OPTIONS
* - Exclude additional public endpoints (signup, reset-password) from authentication
*/
class UserController extends BaseApiController
{
public function behaviors(): array
{
$behaviors = parent::behaviors();
// Override allowed HTTP methods for CORS preflight specifically for UserController
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
// Extend 'except' so signup and reset-password actions do not require auth
$behaviors['authenticator']['except'] = array_merge(
$behaviors['authenticator']['except'],
['signup', 'reset-password']
);
// Ensure uniqueness after merge in case of duplicates
$behaviors['authenticator']['except'] = array_unique($behaviors['authenticator']['except']);
return $behaviors;
}
// Your API actions (index, view, create, etc) follow here...
}
Summary:
BaseApiController contains standard and reusable REST behaviors.