Oto kompletny przykład API w Yii2 z MySQL wraz z konfiguracją:
1. Struktura katalogów projektu
projekt/
├── config/
│ ├── db.php
│ ├── web.php
│ └── params.php
├── controllers/
│ └── api/
│ └── UserController.php
├── models/
│ └── User.php
├── migrations/
│ └── m240617_120000_create_user_table.php
└── web/
└── index.php
2. Konfiguracja bazy danych (config/db.php)
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2_api',
'username' => 'root',
'password' => 'haslo',
'charset' => 'utf8',
// Schema cache options (for production environment)
'enableSchemaCache' => true,
'schemaCacheDuration' => 60,
'schemaCache' => 'cache',
];
3. Główna konfiguracja (config/web.php)
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'components' => [
'request' => [
'cookieValidationKey' => 'your-secret-key-here',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'enableSession' => false,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'viewPath' => '@app/mail',
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'api/user',
'tokens' => [
'{id}' => '<id:\\d+>',
],
'extraPatterns' => [
'GET search' => 'search',
],
],
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
4. Model User (models/User.php)
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'user';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['username', 'email'], 'required'],
[['username', 'email'], 'string', 'max' => 255],
[['email'], 'email'],
[['email'], 'unique'],
[['username'], 'unique'],
[['password_hash'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['created_at', 'updated_at'], 'integer'],
[['status'], 'default', 'value' => 10],
[['status'], 'in', 'range' => [0, 10]],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
/**
* Finds an identity by the given ID.
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => 10]);
}
/**
* Finds an identity by the given token.
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
/**
* Finds user by username
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => 10]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* {@inheritdoc}
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($insert) {
$this->created_at = time();
}
$this->updated_at = time();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function fields()
{
$fields = parent::fields();
// remove fields that contain sensitive information
unset($fields['auth_key'], $fields['password_hash']);
return $fields;
}
}
5. Kontroler API (controllers/api/UserController.php)
<?php
namespace app\controllers\api;
use Yii;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use app\models\User;
use yii\data\ActiveDataProvider;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
public function behaviors()
{
$behaviors = parent::behaviors();
// Uwierzytelnianie za pomocą tokena
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
'except' => ['index', 'view', 'search'], // akcje dostępne bez uwierzytelnienia
];
// Format odpowiedzi
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
// Nadpisanie domyślnej akcji index
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$query = User::find();
return new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
]
],
]);
}
/**
* Wyszukiwanie użytkowników
*/
public function actionSearch()
{
$params = Yii::$app->request->queryParams;
$query = User::find();
// Filtrowanie po username
if (!empty($params['username'])) {
$query->andWhere(['like', 'username', $params['username']]);
}
// Filtrowanie po email
if (!empty($params['email'])) {
$query->andWhere(['like', 'email', $params['email']]);
}
// Filtrowanie po statusie
if (isset($params['status'])) {
$query->andWhere(['status' => $params['status']]);
}
return new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => isset($params['per-page']) ? $params['per-page'] : 20,
],
]);
}
/**
* Utworzenie nowego użytkownika
*/
public function actionCreate()
{
$model = new User();
$model->load(Yii::$app->request->post(), '');
if (isset(Yii::$app->request->post()['password'])) {
$model->setPassword(Yii::$app->request->post()['password']);
$model->generateAuthKey();
}
if ($model->save()) {
Yii::$app->response->statusCode = 201;
return $model;
} else {
Yii::$app->response->statusCode = 422;
return ['errors' => $model->errors];
}
}
}
6. Migracja bazy danych (migrations/m240617_120000_create_user_table.php)
<?php
use yii\db\Migration;
class m240617_120000_create_user_table extends Migration
{
public function safeUp()
{
$this->createTable('{{%user}}', [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
]);
$this->createIndex('idx-user-username', '{{%user}}', 'username');
$this->createIndex('idx-user-email', '{{%user}}', 'email');
$this->createIndex('idx-user-status', '{{%user}}', 'status');
}
public function safeDown()
{
$this->dropTable('{{%user}}');
}
}
7. Plik .htaccess (web/.htaccess)
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
8. Przykłady użycia API
# Pobranie listy użytkowników
GET /api/users
# Pobranie konkretnego użytkownika
GET /api/users/1
# Wyszukiwanie użytkowników
GET /api/users/search?username=john&status=10
# Utworzenie nowego użytkownika
POST /api/users
Content-Type: application/json
{
"username": "john_doe",
"email": "john@example.com",
"password": "secret123"
}
# Aktualizacja użytkownika
PUT /api/users/1
Content-Type: application/json
Authorization: Bearer your-auth-token
{
"email": "newemail@example.com"
}
# Usunięcie użytkownika
DELETE /api/users/1
Authorization: Bearer your-auth-token
9. Uruchomienie migracji
php yii migrate
To kompletne API w Yii2 z MySQL. Możesz je rozbudować o dodatkowe funkcjonalności, takie jak:
- Walidacja danych
- Obsługa relacji
- Zaawansowane filtrowanie
- Paginacja
- Sortowanie
- Uwierzytelnianie JWT
- Rate limiting