Quantcast
Channel: Live News for Yii Framework
Viewing all 3378 articles
Browse latest View live

[extension] abushamleh/yii2-opentok

$
0
0

yii2-opentok

  1. Installation
  2. Working with SIP Interconnect
  3. Force Disconnect
  4. Sending Signals
  5. Samples
  6. Documentation

Yii2 client for opentok (http://www.tokbox.com/opentok)

Installation

  1. Run the Composer command to install the latest version:

    `bash composer require abushamleh/yii2-opentok "dev-master" `

  2. Add the component to config/main.php

    `php 'components' => [

     // ...
     'opentok' => [
         'class'      => 'abushamleh\opentok\Client',
         'api_key'    => 'your api key',
         'api_secret' => 'your secret key',
     ],
     // ...
    

    ], `

    Creating Sessions

To create an OpenTok Session, use the createSession($options) method of the OpenTok\OpenTok class. The $options parameter is an optional array used to specify the following:

  • Setting whether the session will use the OpenTok Media Router or attempt to send streams directly between clients.

  • Setting whether the session will automatically create archives (implies use of routed session)

  • Specifying a location hint.

The getSessionId() method of the OpenTok\Session instance returns the session ID, which you use to identify the session in the OpenTok client libraries.

use OpenTok\MediaMode;
use OpenTok\ArchiveMode;

// Create a session that attempts to use peer-to-peer streaming:
$session = Yii::$app->opentok->createSession();

// A session that uses the OpenTok Media Router, which is required for archiving:
$session = Yii::$app->opentok->createSession(array( 'mediaMode' => MediaMode::ROUTED ));

// A session with a location hint:
$session = Yii::$app->opentok->createSession(array( 'location' => '12.34.56.78' ));

// An automatically archived session:
$sessionOptions = array(
    'archiveMode' => ArchiveMode::ALWAYS,
    'mediaMode' => MediaMode::ROUTED
);
$session = Yii::$app->opentok->createSession($sessionOptions);


// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
Generating Tokens

Once a Session is created, you can start generating Tokens for clients to use when connecting to it. You can generate a token either by calling the generateToken($sessionId, $options) method of the OpenTok\OpenTok class, or by calling the generateToken($options) method on the OpenTok\Session instance after creating it. The $options parameter is an optional array used to set the role, expire time, and connection data of the Token. For layout control in archives and broadcasts, the initial layout class list of streams published from connections using this token can be set as well.

use OpenTok\Session;
use OpenTok\Role;

// Generate a Token from just a sessionId (fetched from a database)
$token = Yii::$app->opentok->generateToken($sessionId);
// Generate a Token by calling the method on the Session (returned from createSession)
$token = $session->generateToken();

// Set some options in a token
$token = $session->generateToken(array(
    'role'       => Role::MODERATOR,
    'expireTime' => time()+(7 * 24 * 60 * 60), // in one week
    'data'       => 'name=Johnny',
    'initialLayoutClassList' => array('focus')
));
Working with Streams

You can get information about a stream by calling the getStream($sessionId, $streamId) method of the OpenTok\OpenTok class.

use OpenTok\Session;

// Get stream info from just a sessionId (fetched from a database)
$stream = Yii::$app->opentok->getStream($sessionId, $streamId);

// Stream properties
$stream->id; // string with the stream ID
$stream->videoType; // string with the video type
$stream->name; // string with the name
$stream->layoutClassList; // array with the layout class list

You can get information about all the streams in a session by calling the listStreams($sessionId) method of the OpenTok\OpenTok class.

use OpenTok\Session;

// Get list of streams from just a sessionId (fetched from a database)
$streamList = Yii::$app->opentok->listStreams($sessionId);

$streamList->totalCount(); // total count
Working with Archives

You can only archive sessions that use the OpenTok Media Router (sessions with the media mode set to routed).

You can start the recording of an OpenTok Session using the startArchive($sessionId, $name) method of the OpenTok\OpenTok class. This will return an OpenTok\Archive instance. The parameter $archiveOptions is an optional array and is used to assign a name, whether to record audio and/or video, the desired output mode for the Archive, and the desired resolution if applicable. Note that you can only start an Archive on a Session that has clients connected.

// Create a simple archive of a session
$archive = Yii::$app->opentok->startArchive($sessionId);


// Create an archive using custom options
$archiveOptions = array(
    'name' => 'Important Presentation',     // default: null
    'hasAudio' => true,                     // default: true
    'hasVideo' => true,                     // default: true
    'outputMode' => OutputMode::COMPOSED,   // default: OutputMode::COMPOSED
    'resolution' => '1280x720'              // default: '640x480'
);
$archive = Yii::$app->opentok->startArchive($sessionId, $archiveOptions);

// Store this archiveId in the database for later use
$archiveId = $archive->id;

If you set the outputMode option to OutputMode::INDIVIDUAL, it causes each stream in the archive to be recorded to its own individual file. Please note that you cannot specify the resolution when you set the outputMode option to OutputMode::INDIVIDUAL. The OutputMode::COMPOSED setting (the default) causes all streams in the archive to be recorded to a single (composed) file.

Note that you can also create an automatically archived session, by passing in ArchiveMode::ALWAYS as the archiveMode key of the options parameter passed into the OpenTok->createSession() method (see "Creating Sessions," above).

You can stop the recording of a started archive using the stopArchive($archiveId) method of the OpenTok\OpenTok object. You can also do this using the stop() method of the OpenTok\Archive instance.

// Stop an Archive from an archiveId (fetched from database)
Yii::$app->opentok->stopArchive($archiveId);
// Stop an Archive from an Archive instance (returned from startArchive)
$archive->stop();

To get an OpenTok\Archive instance (and all the information about it) from an archive ID, use the getArchive($archiveId) method of the OpenTok\OpenTok class.

$archive = Yii::$app->opentok->getArchive($archiveId);

To delete an Archive, you can call the deleteArchive($archiveId) method of the OpenTok\OpenTok class or the delete() method of an OpenTok\Archive instance.

// Delete an Archive from an archiveId (fetched from database)
Yii::$app->opentok->deleteArchive($archiveId);
// Delete an Archive from an Archive instance (returned from startArchive, getArchive)
$archive->delete();

You can also get a list of all the Archives you've created (up to 1000) with your API Key. This is done using the listArchives($offset, $count) method of the OpenTok/OpenTok class. The parameters $offset and $count are optional and can help you paginate through the results. This will return an instance of the OpenTok\ArchiveList class.

$archiveList = Yii::$app->opentok->listArchives();

// Get an array of OpenTok\Archive instances
$archives = $archiveList->getItems();
// Get the total number of Archives for this API Key
$totalCount = $archiveList->totalCount();

For composed archives, you can change the layout dynamically, using the updateArchiveLayout($archiveId, $layoutType) method:

use OpenTok\OpenTok;

$layout Layout::getPIP(); // Or use another get method of the Layout class.
Yii::$app->opentok->updateArchiveLayout($archiveId, $layout);

You can set the initial layout class for a client's streams by setting the layout option when you create the token for the client, using the OpenTok->generateToken() method or the Session->generateToken() method. And you can change the layout classes for a stream by calling the OpenTok->updateStream() method.

Setting the layout of composed archives is optional. By default, composed archives use the "best fit" layout (see Customizing the video layout for composed archives).

For more information on archiving, see the OpenTok archiving developer guide.

Working with Broadcasts

You can only start live streaming broadcasts for sessions that use the OpenTok Media Router (sessions with the media mode set to routed).

Start the live streaming broadcast of an OpenTok Session using the startBroadcast($sessionId, $options) method of the OpenTok\OpenTok class. This will return an OpenTok\Broadcast instance. The $options parameter is an optional array used to assign a layout type for the broadcast.

// Start a live streaming broadcast of a session
$broadcast = Yii::$app->opentok->startBroadcast($sessionId);


// Start a live streaming broadcast of a session, setting a layout type
$options = array(
    'layout' => Layout::getBestFit()
);
$broadcast = Yii::$app->opentok->startBroadcast($sessionId, $options);

// Store the broadcast ID in the database for later use
$broadcastId = $broadcast->id;

You can stop the live streaming broadcast using the stopBroadcast($broadcastId) method of the OpenTok\OpenTok object. You can also do this using the stop() method of the OpenTok\Broadcast instance.

// Stop a broadcast from an broadcast ID (fetched from database)
Yii::$app->opentok->stopBroadcast($broadcastId);

// Stop a broadcast from an Broadcast instance (returned from startBroadcast)
$broadcast->stop();

To get an OpenTok\Broadcast instance (and all the information about it) from a broadcast ID, use the getBroadcast($broadcastId) method of the OpenTok\OpenTok class.

$broadcast = Yii::$app->opentok->getBroadcast($broadcastId);

You can set change the layout dynamically, using the OpenTok->updateBroadcastLayout($broadcastId, $layout) method:

use OpenTok\OpenTok;

$layout Layout::getPIP(); // Or use another get method of the Layout class.
Yii::$app->opentok->updateBroadcastLayout($broadcastId, $layout);

You can use the Layout class to set the layout types: Layout::getHorizontalPresentation(), Layout::getVerticalPresentation(), Layout::getPIP(), Layout::getBestFit(), Layout::createCustom().

$layoutType = Layout::getHorizontalPresentation();
Yii::$app->opentok->setArchiveLayout($archiveId, $layoutType);

// For custom Layouts, you can do the following
$options = array(
    'stylesheet' => 'stream.instructor {position: absolute; width: 100%;  height:50%;}'
);

$layoutType = Layout::createCustom($options);
Yii::$app->opentok->setArchiveLayout($archiveId, $layoutType);

You can set the initial layout class for a client's streams by setting the layout option when you create the token for the client, using the OpenTok->generateToken() method or the Session->generateToken() method. And you can change the layout classes for a stream by calling the Yii::$app->opentok->updateStream() method.

Setting the layout of live streaming broadcasts is optional. By default, broadcasts use the "best fit" layout (see Configuring video layout for OpenTok live streaming broadcasts).

For more information on live streaming broadcasts, see the OpenTok live streaming broadcasts developer guide.

Force a Client to Disconnect

Your application server can disconnect a client from an OpenTok session by calling the forceDisconnect($sessionId, $connectionId) method of the OpenTok\OpenTok class.

use OpenTok\OpenTok;

// Force disconnect a client connection
Yii::$app->opentok->forceDisconnect($sessionId, $connectionId);
Sending Signals

Once a Session is created, you can send signals to everyone in the session or to a specific connection. You can send a signal by calling the signal($sessionId, $payload, $connectionId) method of the OpenTok\OpenTok class.

The $sessionId parameter is the session ID of the session.

The $payload parameter is an associative array used to set the following:

  • data (string) -- The data string for the signal. You can send a maximum of 8kB.

  • type (string) -- — (Optional) The type string for the signal. You can send a maximum of 128 characters, and only the following characters are allowed: A-Z, a-z, numbers (0-9), '-', '_', and '~'.

The $connectionId parameter is an optional string used to specify the connection ID of a client connected to the session. If you specify this value, the signal is sent to the specified client. Otherwise, the signal is sent to all clients connected to the session.

use OpenTok\OpenTok;

// Send a signal to a specific client
$signalPayload = array(
    'data' => 'some signal message',
    'type' => 'signal type'
);
$connectionId = 'da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf';
Yii::$app->opentok->signal($sessionId, $signalPayload, $connectionId);

// Send a signal to everyone in the session
$signalPayload = array(
    'data' => 'some signal message',
    'type' => 'signal type'
);
Yii::$app->opentok->signal($sessionId, $signalPayload);

For more information, see the OpenTok signaling developer guide.

Working with SIP Interconnect

You can add an audio-only stream from an external third-party SIP gateway using the SIP Interconnect feature. This requires a SIP URI, the session ID you wish to add the audio-only stream to, and a token to connect to that session ID.

To initiate a SIP call, call the dial($sessionId, $token, $sipUri, $options) method of the OpenTok\OpenTok class:

$sipUri = 'sip:user@sip.partner.com;transport=tls';

$options = array(
  'headers' =>  array(
    'X-CUSTOM-HEADER' => 'headerValue'
  ),
  'auth' => array(
    'username' => 'username',
    'password' => 'password'
  ),
  'secure' => true,
  'from' => 'from@example.com'
);

Yii::$app->opentok->dial($sessionId, $token, $sipUri, $options);

For more information, see the OpenTok SIP Interconnect developer guide.

Force Disconnect

Your application server can disconnect a client from an OpenTok session by calling the forceDisconnect($sessionId, $connectionId) method of the OpenTok\OpenTok class.

use OpenTok\OpenTok;

// Force disconnect a client connection
Yii::$app->opentok->forceDisconnect($sessionId, $connectionId);

Sending Signals

Once a Session is created, you can send signals to everyone in the session or to a specific connection. You can send a signal by calling the signal($sessionId, $payload, $connectionId) method of the OpenTok\OpenTok class.

The $sessionId parameter is the session ID of the session.

The $payload parameter is an associative array used to set the following:

  • data (string) -- The data string for the signal. You can send a maximum of 8kB.

  • type (string) -- — (Optional) The type string for the signal. You can send a maximum of 128 characters, and only the following characters are allowed: A-Z, a-z, numbers (0-9), '-', '_', and '~'.

The $connectionId parameter is an optional string used to specify the connection ID of a client connected to the session. If you specify this value, the signal is sent to the specified client. Otherwise, the signal is sent to all clients connected to the session.

use OpenTok\OpenTok;

// Send a signal to a specific client
$signalPayload = array(
    'data' => 'some signal message',
    'type' => 'signal type'
);
$connectionId = 'da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf';
Yii::$app->opentok->signal($sessionId, $signalPayload, $connectionId);

// Send a signal to everyone in the session
$signalPayload = array(
    'data' => 'some signal message',
    'type' => 'signal type'
);
Yii::$app->opentok->signal($sessionId, $signalPayload);

For more information, see the OpenTok signaling developer guide.

Samples

There are three sample applications included in this repository. To get going as fast as possible, clone the whole repository and follow the Walkthroughs:

Documentation

Reference documentation is available at https://tokbox.com/developer/sdks/php/reference/index.html.


[extension] abushamleh/yii2-toast

$
0
0
  1. Installation
  2. Usage

Installation

Run the Composer command to install the latest version: composer require abushamleh/yii2-toast "dev-master"

Usage

ToastAlert
use abushamleh\toast\ToastAlert;

echo ToastAlert::widget([
    'options'   => [],
    'heading'   => 'heading',
    'text'      => 'text',
    'type'      => 'type',
]);

ToastBlock

ToastBlock widget renders a message from session flash. All flash messages are displayed in the sequence they were assigned using setFlash. `php use abushamleh\toast\ToastBlock;

//You can set message as following: Yii::$app->session->setFlash('error', 'This is the message'); Yii::$app->session->setFlash('success', 'This is the message'); Yii::$app->session->setFlash('info', 'This is the message'); Yii::$app->session->setFlash('info', ['heading' => 'Message title' 'text' => 'This is the message']);

//Multiple messages could be set as follows: Yii::$app->session->setFlash('error', ['Error 1', 'Error 2']); Yii::$app->session->setFlash('error', [['heading' => 'Message title' 'text' => 'This is the message'], 'Error 2']);

echo ToastBlock::widget([

'options' => []

]);


[extension] devzyj/yii2-attribute-cache-behavior

$
0
0

ActiveRecord attribute cache behavior

  1. Installation
  2. Usage

提供了一些缓存 ActiveRecord 属性的方法。并且当某些事件发生时,自动使缓存失效。

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist "devzyj/yii2-attribute-cache-behavior" "~1.0"

or add

"devzyj/yii2-attribute-cache-behavior" : "~1.0"

to the require section of your application's composer.json file.

Usage

// User.php
class User extends \yii\db\ActiveRecord
{
    use \devzyj\behaviors\ActiveCacheBehaviorTrait;
    
    public function behaviors()
    {
        return [
            [
                'class' => 'devzyj\behaviors\ActiveCacheBehavior',
                //'cache' => 'cache',
                //'defaultDuration' => 604800,
                //'baseModelCacheKey' => ['User', 'PrimaryKey'],
                //'keyAttributes' => static::primaryKey(),
                //'valueAttributes' => $this->attributes(),
            ],
        ];
    }
}


// Using trait methods
// Returns a single active record model instance.
// Sets cache value if there is no cache available for the `$primaryKey`.
$user = User::findOrSetOneByAttribute($primaryKey);

// No changed, cache value exists.
$user->save();

// Changed, cache value not exists.
$user->name = 1;
$user->save();

// Deleted, cache value not exists.
$user->delete();

// Gets cache value for model instance.
$user->getActiveCache();

// Checks cache value exists for model instance.
$user->existsActiveCache();

// Sets cache value for model instance.
$user->setActiveCache();

// Adds cache value for model instance.
$user->addActiveCache();

// Deletes cache value for model instance.
$user->deleteActiveCache();


// Using single key attribute
// ActiveCacheBehavior::$keyAttributes = ['id']
$id = 1;

// get cache
User::instance()->getModelCacheByAttribute($id);
// OR
User::instance()->getModelCache(['id' => $id]);

// exists cache
User::instance()->existsModelCacheByAttribute($id);
// OR
User::instance()->existsModelCache(['id' => $id]);

// set cache
User::instance()->setModelCacheByAttribute($id, $value, $duration, $dependency);
// OR
User::instance()->setModelCache(['id' => $id], $value, $duration, $dependency);

// add cache
User::instance()->addModelCacheByAttribute($id, $value, $duration, $dependency);
// OR
User::instance()->addModelCache(['id' => $id], $value, $duration, $dependency);

// delete cache
User::instance()->deleteModelCacheByAttribute($id);
// OR
User::instance()->deleteModelCache(['id' => $id]);

// get or set cache
User::instance()->getOrSetModelCacheByAttribute($id, function ($behavior) use ($id) {
    $condition = $behavior->ensureActiveKeyAttribute($id);
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);
// OR
$condition = ['id' => $id];
User::instance()->getOrSetModelCache($condition, function ($behavior) use ($condition) {
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);

// trait method: find and return ActiveRecord from cache or database
User::findOrSetOneByAttribute($id, $duration, $dependency);


// Using composite key attribute
// ActiveCacheBehavior::$keyAttributes = ['id1', 'id2']
$id1 = 1;
$id2 = 2;
$ids = [$id1, $id2];

// get cache
User::instance()->getModelCacheByAttribute($ids);
// OR
User::instance()->getModelCache(['id1' => $id1, 'id2' => $id2]);

// exists cache
User::instance()->existsModelCacheByAttribute($ids);
// OR
User::instance()->existsModelCache(['id1' => $id1, 'id2' => $id2]);

// set cache
User::instance()->setModelCacheByAttribute($ids, $value, $duration, $dependency);
// OR
User::instance()->setModelCache(['id1' => $id1, 'id2' => $id2], $value, $duration, $dependency);

// add cache
User::instance()->addModelCacheByAttribute($ids, $value, $duration, $dependency);
// OR
User::instance()->addModelCache(['id1' => $id1, 'id2' => $id2], $value, $duration, $dependency);

// delete cache
User::instance()->deleteModelCacheByAttribute($ids);
// OR
User::instance()->deleteModelCache(['id1' => $id1, 'id2' => $id2]);

// get or set cache
User::instance()->getOrSetModelCacheByAttribute($ids, function ($behavior) use ($ids) {
    $condition = $behavior->ensureActiveKeyAttribute($ids);
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);
// OR
$condition = ['id1' => $id1, 'id2' => $id2];
User::instance()->getOrSetModelCache($condition, function ($behavior) use ($condition) {
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);

// trait method: find and return ActiveRecord from cache or database
User::findOrSetOneByAttribute($ids, $duration, $dependency);


// Using database transactions, and the `commit()` time is too long
$transaction = $db->beginTransaction();
try {
    // old cache key.
    $oldKey = $model->getActiveCacheKey();
    
    // update
    $model->attributes = $attributes;
    $model->save();
    $transaction->commit();
    
    // delete old cache.
    $model->deleteModelCache($oldKey);
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
}

[extension] devzyj/yii2-rest

$
0
0

REST Extension for Yii2

  1. Installation
  2. Usage
  3. Controllers
  4. UrlRule
  5. Actions
  6. Events
  7. Behaviors

增强 yiisoft/yii2-rest 功能,在 Actions 中增加事件。

并且增加了批量操作的 Actions

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist "devzyj/yii2-rest" "~1.0.0"

or add

"devzyj/yii2-rest" : "~1.0.0"

to the require section of your application's composer.json file.

Usage

// UserController.php
class UserController extends \devzyj\rest\ActiveController
{
    public $modelClass = 'app\models\User';
    //public $searchModelClass` = 'app\models\UserSearch';
    //public $notFoundMessage = 'User not found: `{id}`';
    //public $allowedCount = 100;
    //public $manyResourcesMessage = 'The number of users requested cannot exceed `{allowedCount}`.';
}

// config.php
return [
    'components' => [
        'urlManager' => [
            ......
            'rules' => [
                [
                    'class' => 'devzyj\rest\UrlRule',
                    'controller' => 'user',
                    //'extraTokens' => ['{account}' => '<account:\\w[\\w]*>'],
                ]
            ]
        ],
    ],
];

调用方法,只列出部分新增的 API:

  • POST /users/validate: 验证创建一个新用户时的数据
  • PATCH /users/123/validate and PUT /users/123/validate: 验证更新用户 123 时的数据
  • POST /users/batch: 创建多个新用户,
  • PATCH /users/batch and PUT /users/batch: 更新多个用户
  • GET /users/10;11;12: 显示用户 10, 11 和 12 的信息
  • DELETE /users/10;11;12: 删除用户 10, 11 和 12

创建多个新用户时的数据格式:

-d [
    {"username": "example1", "email": "user1@example.com"},
    {"username": "example2", "email": "user2@example.com"}
]

更新用户 123 和 456 时的数据格式:

-d {
    "123": {"username": "example1", "email": "user1@example.com"},
    "456": {"username": "example2", "email": "user2@example.com"}
}

Controllers

  • ActiveController
    • 增加 $searchModelClass 查询数据的模型类名,如果不设置,则使用 $modelClass
    • 增加 $notFoundMessage 模型不存在时的错误信息
    • 增加 $allowedCount 允许批量执行的资源个数
    • 增加 $manyResourcesMessage 批量操作请求资源过多的错误信息
    • 增加 checkActionAccess($action, $params = []) 检查用户是否有执行当前动作的权限
    • 增加 checkModelAccess($model, $action, $params = []) 检查用户是否有执行数据模型的权限
    • 废弃 checkAccess()

UrlRule

  • 增加 $extraTokens 额外的令牌列表。

Actions

修改的 Actions:

  • IndexAction
    • 增加 afterPrepareDataProvider 事件。
  • ViewAction
    • 增加 afterPrepareModel 事件。
  • CreateAction
    • 增加 beforeLoadModel 事件。
    • 增加 afterLoadModel 事件。
    • 增加 beforeProcessModel 事件。
    • 增加 afterProcessModel 事件。
  • UpdateAction
    • 增加 afterPrepareModel 事件。
    • 增加 beforeLoadModel 事件。
    • 增加 afterLoadModel 事件。
    • 增加 beforeProcessModel 事件。
    • 增加 afterProcessModel 事件。
  • DeleteAction
    • 增加 afterPrepareModel 事件。
    • 增加 beforeProcessModel 事件。
    • 增加 afterProcessModel 事件。

增加的 Actions:

  • CreateValidateAction 创建新模型时,验证数据。
    • beforeLoadModel
    • afterLoadModel
    • beforeProcessModel
  • UpdateValidateAction 更新模型时,验证数据。
    • afterPrepareModel
    • beforeLoadModel
    • afterLoadModel
    • beforeProcessModel
  • BatchViewAction 显示多个模型。
    • afterPrepareModel
  • BatchCreateAction 创建多个新模型。
    • beforeLoadModel
    • afterLoadModel
    • beforeProcessModel
    • afterProcessModel
    • afterProcessModels
  • BatchUpdateAction 更新多个模型。
    • afterPrepareModel
    • beforeLoadModel
    • afterLoadModel
    • beforeProcessModel
    • afterProcessModel
    • afterProcessModels
  • BatchDeleteAction 删除多个模型。
    • afterPrepareModel
    • beforeProcessModel
    • afterProcessModel
    • afterProcessModels

Events

  • afterPrepareDataProvider 在准备完数据源后触发的事件。
  • afterPrepareModel 在准备完模型后触发的事件。
  • beforeLoadModel 在模型加载数据前触发的事件,如果返回 false,则阻止模型加载数据。
  • afterLoadModel 在模型成功加载完数据后触发的事件。
  • beforeProcessModel 在处理模型前触发的事件,如果返回 false,则阻止处理模型。
  • afterProcessModel 在成功处理完模型后触发的事件。
  • afterProcessModels 在处理完模型列表后触发的事件。

在批量动作中会多次调用的事件:

  • afterPrepareModel
  • beforeLoadModel
  • afterLoadModel
  • beforeProcessModel
  • afterProcessModel

事件参数说明:

  • 事件参数的类型为 ActionEvent
  • ActionEvent::$object 执行事件时的数据对像,以下列出的是对应事件中的对像类型。
    • afterPrepareDataProvider\yii\data\ActiveDataProvider
    • afterPrepareModel\yii\db\ActiveRecord
    • beforeLoadModelArray
    • afterLoadModel\yii\db\ActiveRecord
    • beforeProcessModel\yii\db\ActiveRecord
    • afterProcessModel\yii\db\ActiveRecord
    • afterProcessModels\devzyj\rest\BatchResult

Behaviors

  • EagerLoadingBehavior 需要手动附加到 IndexAction,可以即时加载指定的额外资源,防止多次查询。

[extension] matthew-p/yii2-models-select

$
0
0

Select models widget for Yii2

  1. Installation
  2. Usage

Find and select models in select2 input.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist matthew-p/yii2-models-select "*"

or add

"matthew-p/yii2-models-select": "*"

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your code by:

$form->field($model, 'attribute')->widget(MPModelSelect::class, [
    'searchModel'     => YouActiveRecordModel::class,
    'valueField'      => 'id',
    'titleField'      => 'title',
    'searchFields'    => [
        // convert to orWhere 'id' => query-string and etc.
        'id', 'title', 
        // add related input (will be added to data request and conver to ->andWhere 'category_id' => request value)
        'category_id' => new JsExpression('$("#category-id").val()'),
        // more examples see MPModelSelect::searchFields
    ],
    'dropdownOptions' => [
        'options'       => [
            'placeholder' => Yii::t('app', 'Select models ...'),
            'multiple'    => true,
        ],
        'pluginOptions' => [
            'minimumInputLength' => 1,
        ],
    ],
])

Add action in controller: `php class SampleController extends Controller { ...

public function actions(): array
{
    return array_merge(parent::actions(), [
        'model-search' => [
            'class' => MPModelSelectAction::class,
        ],
    ]);
}

... } `

Define encryption key in params.php: ` 'MPModelSelect' => [

'encryptionKey' => 'RandomKey',

], `

That's all. Check it.

[news] ApiDoc extension version 2.1.1 released

$
0
0

We are very pleased to announce the release of the ApiDoc extension version 2.1.1.

This release fixes some issues with wrongly formatted PHPDoc and includes support for {@inheritdoc} tags. It also improves Guide rendering by adding a table of contents if there is more than one headline.

Markdown code highlighting has been extracted into a trait MarkdownHighlightTrait, which can be re-used in different contexts.

See the CHANGELOG for a full list of changes.

You may discuss this release on the forum.

[wiki] Batch Gridview data ajax send splitted in chunks displaying bootstrap Progress bar

$
0
0

The scenario in which this wiki can be useful is when you have to send an (huge) array of model ids and perform a time consuming computation with it like linking every model to other models. The idea is to split the array into smaller arrays and perform sequential ajax requests, showing the calculation progress using a Bootstrap Progress bar.

I have created a Country model and generated the CRUD operations using Gii. The model class look like this:

namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "country".
 *
 * @property string $code
 * @property string $name
 * @property int $population
 *
 */
class Country extends \yii\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return 'country';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['code', 'name'], 'required'],
            [['population'], 'integer'],
            [['code'], 'string', 'max' => 3],
            [['name'], 'string', 'max' => 52],
            [['code'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'code' => 'Code',
            'name' => 'Name',
            'population' => 'Population',
        ];
    }
    /**
     * 
     * @return array
     */
    public static function getCodes(){
        return array_keys(ArrayHelper::map(Country::find()->select('code')->asArray()->all(), 'code', 'code'));
    }
}

I have also created another model that will take care to validate the ids and perform the time consuming calculation through the process() function. (in this example I just use a sleep(1) that will wait for one second for each element of the $codes array). I also want to keep track of the processed models, incrementing the $processed class attribute.

<?php

namespace app\models;

use app\models\Country;

/**
 * Description of BatchProcessForm
 *
 * @author toaster
 */
class BatchProcessForm extends \yii\base\Model {

    /**
     * The codes to process
     * @var string
     */
    public $codes;

    /**
     * The number of codes processed
     * @var integer
     */
    public $processed = 0;

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            ['codes', 'required'],
            ['codes', 'validateCodes'],
        ];
    }

    /**
     * Check whether codes exists in the database
     * @param type $attribute
     * @param type $params
     * @param type $validator
     */
    public function validateCodes($attribute, $params, $validator) {
        $input_codes = json_decode($this->$attribute);
        if (null == $input_codes || !is_array($input_codes)) {
            $this->addError($attribute, 'Wrong data format');
            return;
        }
        $codes = Country::getCodes();
        if (!array_intersect($input_codes, $codes) == $input_codes) {
            $this->addError($attribute, 'Some codes selected are not recognized');
        }
    }

    /**
     * Process the codes
     * @return boolean true if everything goes well
     */
    public function process() {
        if ($this->validate()) {
            $input_codes = json_decode($this->codes);
            foreach ($input_codes as $code) {
                sleep(1);
                $this->processed++;
            }
            return true;
        }
        return false;
    }

}

The code for the controller action is the following:

/**
 * Process an array of codes
 * @return mixes
 * @throws BadRequestHttpException if the request is not ajax
 */
public function actionProcess(){
    if(Yii::$app->request->isAjax){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = new BatchProcessForm();
        if($model->load(Yii::$app->request->post()) && $model->process()){
            return ['result' => true, 'processed' => $model->processed];
        }
        return ['result' => false, 'error' => $model->getFirstError('codes')];
    }
    throw new \yii\web\BadRequestHttpException;
}

In my index.php view I have added a CheckboxColumn as first column of the Gridview that allows, out of the box, to collect the ids of the models selected via Javascript (in this case the values of the code attribute). I have also added a button-like hyperlink tag to submit the collected data (with id batch_process) and a Bootstrap Progress bar inside a Modal Window. The code of my view is the following:

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;

/* @var $this yii\web\View */
/* @var $searchModel app\models\CountrySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Countries';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="country-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Country', ['create'], ['class' => 'btn btn-success']) ?>
        <?= Html::a('Batch Process', ['process'], ['class' => 'btn btn-info', 'id' => 'batch_process']) ?>
    </p>

    <?=
    GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'options' => [
            'id' => 'country-index'
        ],
        'columns' => [
            ['class' => 'yii\grid\CheckboxColumn'],
            'code',
            'name',
            'population',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]);
    ?>
</div>

<?php Modal::begin(['header' => '<h5 id="progress">0% Complete</h5>', 'id' => 'progress-modal', 'closeButton' => false]); ?>

<?=
yii\bootstrap\Progress::widget([
    'percent' => 0,
     'options' => ['class' => 'progress-success active progress-striped']
]);
?>

<?php Modal::end(); ?>

<?php $this->registerJsFile('@web/js/main.js', ['depends' => [\app\assets\AppAsset::class]]); ?>

The Javascript file that split in chunks the array and send each chunk sequentially is main.js. Although I have registered the Javascript file using registerJsFile() method I highly recommend to better handle and organize js files using Asset Bundles. Here is the code:


function updateProgressBar(percentage) {
    var perc_string = percentage + '% Complete';
    $('.progress-bar').attr('aria-valuenow', percentage);
    $('.progress-bar').css('width', percentage + '%');
    $('#pb-small').text(perc_string);
    $('#progress').text(perc_string);
}

function disposeProgressBar(message) {
    alert(message);
    $('#progress-modal').modal('hide');
}

function showProgressBar() {
    var perc = 0;
    var perc_string = perc + '% Complete';
    $('.progress-bar').attr('aria-valuenow', perc);
    $('.progress-bar').css('width', perc + '%');
    $('#pb-small').text(perc_string);
    $('#progress').text(perc_string);
    $('#progress-modal').modal('show');
}

function batchSend(set, iter, take, processed) {
    var group = iter + take < set.length ? iter + take : set.length;
    var progress = Math.round((group / set.length) * 100);
    var dataObj = [];
    for (var i = iter; i < group; i++) {
        dataObj.push(set[i]);
    }
    iter += take;
    $.ajax({
        url: '/country/process', ///?r=country/process
        type: 'post',
        data: {'BatchProcessForm[codes]': JSON.stringify(dataObj)},
        success: function (data) {
            if (data.result) {
                updateProgressBar(progress);
                processed += data.processed;
                if (progress < 100) {
                    batchSend(set, iter, take, processed);
                } else {
                    var plural = processed == 1 ? 'country' : 'countries';
                    disposeProgressBar(processed + ' ' + plural + ' correctly processed');
                }
                return true;
            }
            disposeProgressBar(data.error);
            return false;
        },
        error: function () {
            disposeProgressBar('Server error, please try again later');
            return false;
        }
    });
}

$('#batch_process').on('click', function (e) {
    e.preventDefault();
    var keys = $('#country-index').yiiGridView('getSelectedRows');
    if (keys.length <= 0) {
        alert('Select at least one country');
        return false;
    }
    var plural = keys.length == 1 ? 'country' : 'countries';
    if (confirm(keys.length + ' ' + plural + ' selected.. continue?')) {
        showProgressBar();
        batchSend(keys, 0, 5, 0);
    }
});

The first three functions take care to show, update and hide the progress bar inside the modal window, while the batchSend function perform the array split and, using recursion, send the data through post ajax request, encoding the array as JSON string and calling itself until there is no more chunks to send. The last lines of code bind the click event of the #batch_process button checking if at least one row of Gridview has been selected. The number of elements on each array chunk can be set as the third argument of the batchSend function (in my case 5), you can adjust it accordingly. The first parameter is the whole array obtained by the yiiGridView('getSelectedRows') function. The final result is something like this: batch_send1.gif ...looks cool, isn't it?

[extension] panlatent/yii2-odoo

$
0
0

logo.svg?sanitize=true

Odoo JSON-RPC Client, Query and ActiveRecord for Yii2


This extension provides the [Odoo](https://www.odoo.com) integration for the [Yii framework 2.0](http://www.yiiframework.com/). It includes [Web Service API](https://www.odoo.com/documentation/10.0/api_integration.html) support and also implements the `Query` and `ActiveRecord` pattern. Documentation is at [Read The Docs](https://yii2-odoo.panlatent.com/). [![Build Status](https://travis-ci.org/panlatent/yii2-odoo.svg)](https://travis-ci.org/panlatent/yii2-odoo) [![Coverage Status](https://coveralls.io/repos/github/panlatent/yii2-odoo/badge.svg)](https://coveralls.io/github/panlatent/yii2-odoo) [![Latest Stable Version](https://poser.pugx.org/panlatent/yii2-odoo/v/stable.svg)](https://packagist.org/packages/panlatent/yii2-odoo) [![Total Downloads](https://poser.pugx.org/panlatent/yii2-odoo/downloads.svg)](https://packagist.org/packages/panlatent/yii2-odoo) [![Latest Unstable Version](https://poser.pugx.org/panlatent/yii2-odoo/v/unstable.svg)](https://packagist.org/packages/panlatent/yii2-odoo) [![License](https://poser.pugx.org/panlatent/yii2-odoo/license.svg)](https://packagist.org/packages/panlatent/yii2-odoo) Requirements ------------ + PHP 7.0 or higher Installation ------------ The preferred way to install this extension is through [composer](http://getcomposer.org/download/). Either run ``` php composer.phar require --prefer-dist panlatent/yii2-odoo "*" ``` or add ``` "panlatent/yii2-odo": "*" ``` to the require section of your `composer.json` file. Usage ----- Once the extension is installed, simply use it in your code by : Add the component to your application. ```php 'components' => [ 'odoo' => [ 'class' => 'panlatent\odoo\Connection', 'dsn' => 'localhost:8000/jsonrpc', 'database' => '', 'username' => '', 'password' => '', ] ] ``` The extension support Yii2 Debug extension: Add the panel component to your application. ```php 'modules' => [ 'debug' => [ 'panels' => [ 'odoo' => [ 'class' => panlatent\odoo\debug\OdooPanel::class, ] ] ] ] ``` License ------- The Yii2 Odoo is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).


[extension] mailboxvalidator/mailboxvalidator-yii

$
0
0

MailboxValidator Yii Email Validation Extension

  1. Installation
  2. Dependencies
  3. Methods
  4. Usage
  5. Errors
  6. Copyright

MailboxValidator Yii Email Validation Extension provides an easy way to call the MailboxValidator API which validates if an email address is valid.

Installation

Install this extension by using Composer:

`composer require mailboxvalidator/mailboxvalidator-yii`

Dependencies

An API key is required for this module to function.

Go to https://www.mailboxvalidator.com/plans#api to sign up for FREE API plan and you'll be given an API key.

After you get your API key, open your `config/params.php` and add the following line into the array:

'mbvAPIKey' => 'PASTE_YOUR_API_KEY_HERE',

You can also set you api key in controller after calling library. Just do like this:

$mbv = new SingleValidation('PASTE_YOUR_API_KEY_HERE');

or like this:

['email', MailboxValidator::className(), 'option'=>'YOUR_SELECTED_OPTION','api_key'=>'PASTE_YOUR_API_KEY_HERE',],

Methods

Below are the methods supported in this library.

Method Name Description
ValidateEmail Return the validation result of an email address. Please visit MailboxValidator for the list of the response parameters.
validateFree Check whether the email address is belongs to a free email provider or not. Return Values: True, False
validateDisposable Check whether the email address is belongs to a disposable email provider or not. Return Values: True, False

Usage

Form Validation

To use this library in form validation, first call this library in your model like this:

use MailboxValidator\MailboxValidator;

After that, in the function rules, add the new validator rule for the email:

['YOUR_EMAIL_FIELD_NAME', MailboxValidator::className(), 'option'=>'disposable,free',],

In this line, the extension is been called, and you will need to specify which validator to use. The available validators are disposable and free. After that, refresh you form and see the outcome.

Email Validation

To use this library to get validation result for an email address, firstly load the library in your controller like this:

use MailboxValidator\SingleValidation;

After that, you can get the validation result for the email address like this:

$mbv = new SingleValidation(Yii::$app->params['mbvAPIKey']);
$results = $mbv->FreeEmail('example@example.com');

To pass the result to the view, just simply add the $results to your view loader like this:

return $this->render('YOUR_VIEW_NAME', ['results' => $results]);

And then in your view file, call the validation results. For example:

echo 'email_address = ' . $results->email_address . "<br>";

You can refer the full list of response parameters available at here.

Errors

error_code error_message
100 Missing parameter.
101 API key not found.
102 API key disabled.
103 API key expired.
104 Insufficient credits.
105 Unknown error.

Copyright

Copyright (C) 2018 by MailboxValidator.com, support@mailboxvalidator.com

[extension] rrk

$
0
0
  1. Requirements
  2. Installation
  3. Usage
  4. Resources

...overview of the extension...

Requirements

...requirements of using this extension (e.g. Yii 2.0 or above)...

Installation

...how to install the extension (e.g. composer install extensionname)...

Usage

...how to use this extension...

...can use code blocks like the following...

$model=new User;
$model->save();

Resources

DELETE THIS SECTION IF YOU DO NOT HAVE IT

...external resources for this extension...

  • [Project page](URL to yock

[extension] language/yii2-protobuf

$
0
0

Yii Protobuf Extension is a wrapper for php protobuf c-extension.It provides an easy way to decode/encoder protobuf data with Yii.In addition to,it provides a tool to generate php proto files from .proto.

You must install php c-ext before you can use this extension

Requirements

To use PHP runtime library requires:

  • C extension:protobuf >= 3.5.0
  • PHP package:php >= 7.0.0
  • Yii2.0 or above
Installation

You can install this extension by composer, as follows: `bash composer require language/yii2-protobuf `

Configure

You need to add protobuf parser/formatter for request/response Component, as follows: `php return [

...
'components' => [
        ...
    'request' => [
        // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
        'cookieValidationKey' => 'inwyiHVV0KPon5UhGv6l0QYaWL4SC1ww',
        'parsers' => [
            'application/x-protobuf' => 'Language\Protobuf\ProtobufParser'
        ],
    ],
    'response' => [
        'formatters'=>[
            'protobuf' => [
                'class'=>'Language\Protobuf\ProtobufResponseFormatter',
                'hump'=>true, //By default, the field name is underlined to hump, for example, iphone_num is converted to IphoneNum.
            ],
        ],
    ],
    ...
],

]

As you can see, this extension use ```application/x-protobuf``` Content-Type to distinguish protobuf binary data.So, Client should set Content-Type as 
```application/x-protobuf``` when it send protobuf binary data to Server

### Generate Proto
You can run build.sh shell script to generate proto files after Editing msg.proto. it will generate ```PbApp``` and ```GPBMetadata```.You should always edit .proto instead of editing generated proto files
 ```shell
bash build.sh
Register Proto

You need to register .proto.php files for encode protobuf data after generate proto files.You can create a base controller and register them, As follows:

class BaseController extends Controller
{
    use ProtobufTrait;  //Inject using the trait attribute asProtobuf method

    public function init()
    {
        parent::init();
        // 消息文件注册
        ProtobufManager::register(ROOT . '/proto/msg.proto.php');
    }
}

ProtobufTrait provides `asProtobuf` method to convert php hash table to protobuf data

Usage

You should alway get request params with `$request->getBodyParams()`intead of `$_REQUEST`.ProtobufParser parser protobuf to array `php <?php /**

  • Created by PhpStorm.
  • User: liugaoyun
  • Date: 2018/12/1
  • Time: 下午9:10 */

namespace frontend\controllers;

use Language\Protobuf\ProtobufTrait; use yii\base\Controller;

class TestController extends Controller {

public function actionProtobuf(){
    //params
    $params = \Yii::$app->getRequest()->getBodyParams();

    //TODO:your logic

    //convert array to protobuf
    $data = [
        'UserInfo'=>[
            'OpenUid'=>'xxxx',
            'NickName'=>'xxxx',
            'Age'=>100,
            'Param1'=>1000
        ],
        'AddrList'=>[
            'home'=>[
                'Address'=>'addr1',
                'IphoneNum'=>'153xxxx6476'
            ],
            'company'=>[
                'Address'=>'addr2',
                'IphoneNum'=>'188xxxx7049'
            ],
        ],
        'GoneCities'=>[
            ['Name'=>'Beijing'],
            ['Name'=>'Hangzhou'],
        ]
    ];
    return $this->asProtobuf(['class'=>'PbApp\UserLoginACK', 'data'=>$data]);
}

} `

Sample `text

xxxxxxxxd � home 153xxxx6476 company 188xxxx7049 Beijing

Hangzhou `

Customized Request Struct

By default, protobuf parser can only parser map<string,string> protobuf data as message-defined `proto` `protobuf message Request {

map<string,string>  Headers  = 1;			// Header Params
map<string,string>  BodyParams  = 2;         // Body Params

} `

You can define your request proto, as follows `protobuf message Meta{

repeated    Params = 1;

}

message MyRequest {

 map<string,Meta>  Headers  = 1;			// Header Params
    map<string,Meta>  BodyParams  = 2;         // Body Params

} Then, you should tell ProtobufFormatter which class to serialize Array Data php return [

...
'components' => [
        ...
    'response' => [
        'formatters'=>[
            'protobuf' => [
                'class'=>'Language\Protobuf\ProtobufResponseFormatter',
                'hump'=>true, //By default, the field name is underlined to hump, for example, iphone_num is converted to IphoneNum.
                'requestProtoClass'=>'PbApp\MyRequest'
            ],
        ],
    ],
    ...
],

] `

If you need more flexiable data-struct, you can parser the protobuf raw data, as follows: `php message UserMsgLoginREQ{

string  UserName = 1;
string  Password = 2;

}

message FlexiableRequest {

string ProtoClass  = 1;         // proto class to parser
bytes  ProtoData  = 2;         // bytes protobuf data

} `

FlexiableRequest is a internal proto define. So, don't change the message name.

[extension] widewhale/yii2-debug-vardumper

$
0
0

VarDumper panel for Yii2-debug

This extensions adds a panel which show var dumps using custom VarDumper::dump($var) function.

Installation

Install extention via composer command: `sh composer require widewhale/yii2-debug-vardumper `

Then add panel to your debug config: `php 'modules'=>[

...
'debug'=>[
    ...
    'panels'=>[
        ...
        'vardumper'=>[
            'class'=>'\widewhale\debug\vardumper\panels\VarDumperPanel'
        ]
    ]
]
...

] `

Usage
...

use widewhale\debug\vardumper\components\VarDumper;

...

VarDumper::dump($var);

Since class name same as yii\helpers\VarDumper you basicly can just replace yii\helpers\VarDumper with widewhale\debug\vardumper\components\VarDumper if you're used default VarDumper helper previously.

IMPORTANT If you want to use yii\helpers\VarDumper and widewhale\debug\vardumper\components\VarDumper simultaneously you should use aliases (or fully qualified namespace names) `php use widewhale\debug\vardumper\components\VarDumper; use yii\helpers\VarDumper as YiiVarDumper;

...

VarDumper::dump($var); YiiVarDumper::dump($var);

OR

\widewhale\debug\vardumper\components\VarDumper::dump($var);

 

[news] Gii extension 2.0.8 released

$
0
0

We are very pleased to announce the release of Gii extension version 2.0.8.

Additionally to bug fixes, there is a new option in model generator that allows standardized capitals in class names:

SOME_TABLE -> SomeTable
Other_Table -> OtherTable

instead of

SOME_TABLE -> SOMETABLE
Other_Table -> OtherTable

See the CHANGELOG for details.

[news] PHP 7.3.0 released

[extension] cebe/yii2-lifecycle-behavior

$
0
0

Yii 2 lifecycle behavior

  1. Installation
  2. Usage

Define the lifecycle of a model by defining allowed status changes in terms of a state machine.

Installation

This is an extension for the Yii 2 PHP framework.

Installation is recommended to be done via composer by running:

composer require cebe/yii2-lifecycle-behavior

Alternatively you can add the following to the require section in your composer.json manually and run composer update afterwards:

"cebe/yii2-lifecycle-behavior": "~1.0.0"

Usage

You can add the behavior to an ActiveRecord class. It does not work with yii\base\Model because it relies on the old-attribute feature which is only available in active record.

You can add the behavior to the model by creating a behaviors() method if there is none yet, or add it to the list of exising behaviors.

The following example shows how to define the allowed status changes:

	public function behaviors()
	{
		return [
			'lifecycle' => [
				'class' => 'cebe\lifecycle\LifecycleBehavior',
				'validStatusChanges' => [
					'draft'     => ['ready', 'delivered'],
					'ready'     => ['draft', 'delivered'],
					'delivered' => ['payed', 'archived'],
					'payed'     => ['archived'],
					'archived'  => [],
				],
			],
		];
	}

The above state transitions can be visualized as the following state machine:

Visualization of state transitions


[extension] fl0v/yii2-rollbar

$
0
0

Rollbar for Yii2

  1. Installation
  2. Usage
  3. Payload from your exceptions
  4. Log Target
  5. Rollbar Javascript

This extension is a fork from baibaratsky/yii2-rollbar and eroteev/yii2-rollbar. For Yii 1.x use baibaratsky/yii-rollbar.

Installation

The preferred way to install this extension is through composer.

To install, either run $ php composer.phar require fl0v/yii2-rollbar or add "fl0v/yii2-rollbar": "*" to the require section of your composer.json file.

Usage

  • Add the component configuration in your global config file:
'components' => [
    'rollbar' => [
        'class' => 'fl0v\yii2\rollbar\RollbarLoader',
        'config' => [
            'environment' => '{your_environment}',
            'access_token' => '{rollber_access_token}',
            // other Rollbar config settings
        ],
    ],
]
  • Add the web error handler configuration in your web config file:
'components' => [
    'errorHandler' => [
        'class' => 'fl0v\yii2\rollbar\handlers\WebErrorHandler',
    ],
],
  • Add the console error handler configuration in your console config file:
'components' => [
    'errorHandler' => [
        'class' => 'fl0v\yii2\rollbar\handlers\ConsoleErrorHandler',
    ],
],

Payload from your exceptions

If you want your exceptions to send some additional data to Rollbar, it is possible by implementing PayloadInterface.

use fl0v\yii2\rollbar\PayloadInterface;
 
class SomeException extends \Exception implements PayloadInterface
{
    public function rollbarPayload()
    {
        return ['foo' => 'bar'];
    }
}

Log Target

You may want to collect your logs produced by Yii::error(), Yii::info(), etc. in Rollbar. Put the following code in your config:

'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'fl0v\yii2\rollbar\RollbarTarget',
                'levels' => ['error', 'warning', 'info'], // Log levels you want to appear in Rollbar             
                'categories' => ['application'],
            ],
        ],
    ],
],

Rollbar Javascript

Rollbar offers Javascript debugger aswell, see https://docs.rollbar.com/docs/javascript. To use it in Yii2 there is fl0v\yii2\rollbar\RollbarAsset that you can register in your main template.

RollbarAsset is used independently of the server side component, to configure it use assetManager. For the config part of RollbarAsset checkout Rollbar reference https://docs.rollbar.com/docs/rollbarjs-configuration-reference#section-reference.

'assetManager' => [
    ...
    'bundles' => [
        ....
        'fl0v\yii2\rollbar\RollbarAsset' => [
            // Rollbar configuration
            'config' => [
                'enbaled' => true,
                'accessToken' => '{token}',
                // initialize payload
                'payload' => [
                    'environment' => '{environment}',
                    'client' => [
                        'javascript' => [
                            'code_version' => '...',
                        ],
                    ],
                ],
            ],
            // metrics to add to payload, is called when the asset is registered
            'payload' => function () {
                return [
                    'person' => [
                        'id' => \Yii::$app->has('user') ? (string) \Yii::$app->user->id : null,
                        'username' => \Yii::$app->has('user') && ! \Yii::$app->user->isGuest ? \Yii::$app->user->identity->username : null,
                    ],
                    'custom' => [
                        'myData' => 'asd',
                        'key' => uniqid(),
                    ],
                ];
            ],
        ],
    ],
],

[extension] chsergey/yii2-rest-client

$
0
0

REST Client for Yii 2 (ActiveRecord-like model)

  1. Installation
  2. Usage

Latest Stable Version Total Downloads Latest Unstable Version License Code Climate

This extension provides an interface to work with RESTful API via ActiveRecord-like model in Yii 2.

For HTTP requests thanks to GuzzleHttp

Welcome to PR

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist chsergey/yii2-rest-client:0.1.1

or add

"chsergey/yii2-rest-client": "0.1.1"

to the require section of your composer.json.

Usage

[wiki] (draft) Understanding Yii 3

$
0
0

Understanding Yii 3

  1. Introduction
  2. Yii 3 composer packages
  3. Running your first Yii 3 powered application

Introduction

This document is intended for an audience already familiar with Yii2. It's meant to rassemble all information related to Yii 3 in one place to make it easier to get on track.

Yii 3 is the second major rewrite of the Yii framework.

Originally started in the 2.1 branch, it was later decided to switch to the 3.X series because of all the backward compatibility breakage. Starting with 3.0, Yii will follow the Sementic Versionning.

This rewrite addresses a lot of issues Yii 2 suffered from, like the framework being too coupled with jQuery, bower, bootstrap.

In order to achieve this, the framework source code have been split into several packages, and at its core level, Yii no longer makes assumptions about your web stack.

This re-organisation is also a great new for maintainance, as these packages will be maintained and released separatly, thus allowing more frequent updates.

It's also important to note that the custom PHP class autoloader have also been removed in favor of Composer's PSR-4 implementation. We will see the implications of this change later.

Other new PSR changes:

  • Logging is now compliant with PSR-3
  • Caching is now compliant with PSR-16

You can check the complete CHANGELOG for an exhaustive list of modifications.

Yii 3 composer packages

Here are the new packages introduced in Yii 3, which can be found in this official list.

Let's introduce them briefly:

The Framework

This is the new kernel of Yii. It defines the base framework and its core features like behaviors, i18n, mail, validation..

You will rarely want to directly install yiisoft/yii-core. Instead, you will install one or more of the following:

This three packages, considered as Extensions, are responsible for implementing the basic functionnalities of each "channel" they refer to:

  • yii-console implements all that you need to build a console application (the base Controller for commands, the Command helper, ..)
  • yii-web implements all that you need to build a web application (Assets management, Sessions, Request handling ..)
  • yii-rest implements all that you need to build a REST interface (ActiveController, ..)
Librairies

In Yii 3, libraries do not depend on Yii and are meant to be usable outside the framework. Their package name is yiisoft/something without yii-prefix.

Drivers for yiisoft/db

The various drivers for DB have also been separated into packages:

Extensions

Extensions depends (at least) on yii-core. Aside from the 3 extensions already encountered above (yii-console, yii-web, yii-api), these packages are available

Development
View rendering engines
Data rendering
JS & CSS Frameworks integration
Widgets
Misc
Yii project template and application bases

This is a very basic Yii project template, that you can use to start your development.

You will probably want to pick one or more of these three starters to install in your project next:

Let's try running the web base template in the next section.

Running your first Yii 3 powered application

Let's try running a web application using Yii 3, and the provided project template.

Installing the project template
composer create-project --prefer-dist --stability=dev yiisoft/yii-project-template myapp
cd myapp

Here's the created structure:

.
├── LICENSE
├── README.md
├── composer.json
├── composer.lock
├── config
│   ├── common.php
│   └── params.php
├── docker-compose.yml
├── hidev.yml
├── public
│   ├── assets
│   ├── favicon.ico
│   ├── index.php
│   └── robots.txt
├── runtime
└── vendor

You won't be able to start the web server right away using ./vendor/bin/yii serve, as it will complain about not knowing the "app" class.

In fact, this project template only introduce the bare minimum in your application: Caching, Dependencies injection, and Logging. The template doesn't make an assumption about the kind of application you're building (web, cli, api).

You could start from scratch using this bare template, select the extensions & packages you want to use and start developing, or you can pick one of the three starters provided.

Installing the web starter

Since we're doing a web application, we will need an asset manager. We can pick either one of those:

  • Asset-packagist & composer-merge-plugin (requires only PHP)
  • Foxy (requires npm or yarn)

Let's go with foxy (personal taste since composer is so slow from Tunisia):

composer require "foxy/foxy:^1.0.0"

We can now install the yii-base-web starter and run our application:

composer require yiisoft/yii-base-web
vendor/bin/yii serve

By visiting http://localhost:8080/, you should now see something like this:

[[/Users/didou/Desktop/Screen Shot 2018-12-16 at 10.14.25 PM.png]]

Not really sexy, but well, that's a start!

Checking back our project structure, nothing really changed, aside from the creation of these three entries:

  • node_modules/
  • package-lock.json
  • package.json

So where do what we see in the browser comes from ?

Exploring yiisoft/yii-base-web structure:

If you explore the folder in vendor/yiisoft/yii-base-web, you will see that the template is in fact a project itself, with this structure:

.
├── LICENSE.md
├── README.md
├── composer.json
├── config
│   ├── common.php
│   ├── console.php
│   ├── env.php
│   ├── messages.php
│   ├── params.php
│   └── web.php
├── phpunit.xml.dist
├── public
│   └── css
│       └── site.css
├── requirements.php
├── runtime
└── src
    ├── assets
    │   └── AppAsset.php
    ├── commands
    │   └── HelloController.php
    ├── controllers
    │   └── SiteController.php
    ├── forms
    │   ├── ContactForm.php
    │   └── LoginForm.php
    ├── mail
    │   └── layouts
    ├── messages
    │   ├── et
    │   ├── pt-BR
    │   ├── ru
    │   └── uk
    ├── models
    │   └── User.php
    ├── views
    │   ├── layouts
    │   └── site
    └── widgets
        └── Alert.php

The folders and files should make sense to you if you already developed applications using Yii2 and the basic template.

[extension] yii-insert-multi-rows

$
0
0
  1. Requirements
  2. Installation
  3. Usage

Creates and executes an INSERT SQL statement for several rows.

Requirements

Yii 1.1 or above

Installation

For insert multi rows, Put this code in components folder under GeneralRepository.php file name.

Usage

$rows = array(
     array('id' => 1, 'name' => 'John'),
     array('id' => 2, 'name' => 'Mark')
);
GeneralRepository::insertSeveral(User::model()->tableName(), $rows);

[extension] genxoft/curl

$
0
0

php-curl wrapper

  1. Requirements
  2. Installation
  3. Quick usage
  4. Basic usage
  5. Donate
  6. LICENSE

Simple curl wrapper with REST methods support:

  • GET
  • HEAD
  • POST
  • PUT
  • PATCH
  • DELETE

Requirements

  • PHP 5.4+
  • curl php extension

Installation

The preferred way to install this wrapper is through composer.

php composer.phar require genxoft/curl "*"

or

composer require genxoft/curl "*"

Quick usage

Quick get request
require_once __DIR__ . '/vendor/autoload.php';
use genxoft\curl\Curl;

$result = Curl::QuickGet("http://example.com", ["text_param" => "text_value"]);

You can see also Curl::QuickPost and Curl::QuickJson quick methods

Basic usage

Post request with Json data

Performing post request with Json data and query params

require_once __DIR__ . '/vendor/autoload.php';
use genxoft\curl\Curl;
use genxoft\curl\Request;

$request = new Request("http://example.com");
$request->addGetParam("action", "save")
    ->setJsonBody([
        "name" => "John Smith",
        "age" => 23
    ]);
$curl = new Curl($request);
$response = $curl->post();

if ($response === null) {
    echo $curl->getLastError();
} else {
    if ($response->isSuccess()) {
        echo "Data saved";
    } else {
        echo "HTTP Error: ".$response->getStatusMessage();
    }
}

Donate

btn_donateCC_LG.gif

LICENSE

This curl wrapper is released under the MIT license.

Viewing all 3378 articles
Browse latest View live