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

[news] Queue extension 2.2.0 released

$
0
0

We are very pleased to announce the release of Queue extension version 2.2.0.

The release is fixing important bugs, reduces roundtrips to beanstalk server when removing a job, marking ErrorEvent as deprecated and making job execution result being forwarded to event handler.

Full changelog is available at GitHub.


[extension] diazoxide/yii2-blog

$
0
0

diazoxide/yii2-blog

Advanced Yii2 Blog module. Posts, Categories, Comments, Tags, With Slider Revolution, SEO tags, Social Tags
Features
  • Blog Posts
    • Title
    • Slug
    • Multiple Categories for each post
    • Brief
    • Content
      • Custom Redactor/wysiwyg editor
    • Books
      • Chapters and sub Chapters
      • Nested structure
      • Nested breadcrumbs
      • BBCode support
      • Custom BBCode styling
  • Blog Categories
  • Blog Tags
  • Blog Comments
  • Custom Widgets
    • Dynamic widgets
    • Custom backend panel
    • Custom Styling
    • Custom Javascript
    • Infinite Scroll for each widgted
    • Category integration
  • Slider Revolution

installation

add to composer.json

{
    "require": {
      "diazoxide/yii2-blog": "dev-master"
    }
}

common configuration

 'modules'=>[
     'blog' => [
         'class' => "diazoxide\blog\Module",
         'urlManager' => 'urlManager',
         'imgFilePath' => dirname(__DIR__) . '/public/uploads/img/blog/',
         'imgFileUrl' => '/uploads/img/blog/',
         // You can change any view file for each route
         'frontendViewsMap'=>[
             'blog/default/index'=>'@app/views/blog/index'
         ],
         // You can change any layout for each route
         'frontendLayoutMap'=>[
             'blog/default/view'=>'@app/views/layouts/main-with-two-sidebar',
             'blog/default/archive'=>'@app/views/layouts/main-with-right-sidebar',
         ],
         'homeTitle'=>'Blog title',
         'userModel' => "\app\models\User",
         'userPK' => 'id',
         'userName' => 'username',
         'showClicksInPost'=>false,
         'enableShareButtons' => true,
         'blogPostPageCount' => '10',
         'schemaOrg' => [
             'publisher' => [
                 'logo' => '/path/to/logo.png',
                 'logoWidth' => 200,
                 'logoHeight' => 47,
                 'name' => "Blog title",
                 'phone' => '+1 800 488 80 85',
                 'address' => 'Address 13/5'
             ]
         ]
     ],
 ]

backend configuration

$config['modules']['blog']['controllerNamespace'] = 'diazoxide\blog\controllers\backend';

Migration

after install run migration command

php yii migrate --migrationPath=@vendor/diazoxide/yii2-blog/migrations

Custom urlManager rules for beautiful links

archive url in frontend

https://blog.com/archive

category url in frontend

https://blog.com/category/politics

post url in frontend like a wordpress and seo friendly

https://blog.com/2019/11/21/your-post-slug

 'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        //F.E. https://blog.com/category/politics
        '/category/<slug>' => '/blog/default/archive',
        
        //F.E. https://blog.com/archive
        '/archive' => '/blog/default/archive',
        
        //F.E. https://blog.com/2019/11/21/your-post-slug
        [
            'pattern' => '<year:\d{4}>/<month:\d{2}>/<day:\d{2}>/<slug>',
            'route' => '/blog/default/view',
            'suffix' => '/'
        ],
    ],
],

[news] Yii 2.0.17

$
0
0

We are very pleased to announce the release of Yii Framework version 2.0.17. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.

Version 2.0.17 is a minor release of Yii 2.0 which contains some bugfixes including a security fix.

No known changes that could affect existing applications were made.

Both basic and advanced applications got fixes for recent Codeception, got updated debug and gii versions to version 2.1.0. Basic application now uses swiftmailer 2.1.0.

Thanks to all Yii community members who contribute to the framework, translators who keep documentation translations up to date and community members who answer questions at forums.

There are many active Yii communities so if you need help or want to share your experience, feel free to join them.

Below we summarize some of the enhancements and changes that slipped into this release. A complete list of changes can be found in the CHANGELOG.

[extension] ianikanov/yii2-wce

$
0
0

Widget as Controller Yii2 Extension

  1. Installation
  2. Usage

Ability to generate widgets with interface similar to controller with basic CRUD actions for specific model

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist ianikanov/yii2-wce "dev-master"

or add

"ianikanov/yii2-wce": "dev-master"

to the require section of your composer.json file.

Usage

Once the extension is installed, add new template to your config file : `php if (YII_ENV_DEV) {

$config['modules']['gii'] = [
    'class' => 'yii\gii\Module',      
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],  
    'generators' => [ //here
        'widgetCrud' => [
            'class' => '\ianikanov\wce\templates\crud\Generator',
            'templates' => [
                'WCE' => '@vendor/ianikanov/yii2-wce/templates/crud/default', // template name
            ],
        ],
    ],
];

} `

Then run gii, select "CRUD Controller Widget" fill the form and generate the code.

To use widget in any other form.

To show list of items, for example, the list of Posts related to the current model: `php <?= app\widgets\PostControllerWidget::widget([

'action' => 'index',
'params' => [
    'query' => $model->getPosts(),
],

]) ?> `

To show a single item details, for example the post `php <?= app\widgets\PostControllerWidget::widget([

'action' => 'view',
'params' => [
    'id' => $post_id,
],

]) ?> `

To show create button with modal window: `php <?= app\widgets\PostControllerWidget::widget(['action' => 'create']) ?> `

To show update button with modal window: `php <?= app\widgets\PostControllerWidget::widget(['action' => 'update', 'params'=>['id' => $model->id]]) ?> `

To show delete button: `php <?= app\widgets\PostControllerWidget::widget(['action' => 'delete', 'params'=>['id' => $model->id]]) ?> `

[extension] mihaildev/yii2-elfinder

$
0
0

ElFinder Расширение для Yii 2

  1. Поддерживаемые хранилища
  2. Установка
  3. Настройка
  4. Настройка callback-ов для событий
  5. Настройка Плагинов
  6. Использование
  7. Использование при работе с PathController
  8. CKEditor
  9. Проблемы

ElFinder — файловый менеджер для сайта.

Поддерживаемые хранилища

mihaildev/yii2-elfinder-flysystem - https://github.com/MihailDev/yii2-elfinder-flysystem/

    Local
    Azure
    AWS S3 V2
    AWS S3 V3
    Copy.com
    Dropbox
    FTP
    GridFS
    Memory
    Null / Test
    Rackspace
    ReplicateAdapter
    SFTP
    WebDAV
    PHPCR
    ZipArchive

Установка

Удобнее всего установить это расширение через composer.

Либо запустить

php composer.phar require --prefer-dist mihaildev/yii2-elfinder "*"

или добавить

"mihaildev/yii2-elfinder": "*"

в разделе require вашего composer.json файла.

Настройка

'controllerMap' => [
        'elfinder' => [
            'class' => 'mihaildev\elfinder\Controller',
            'access' => ['@'], //глобальный доступ к фаил менеджеру @ - для авторизорованных , ? - для гостей , чтоб открыть всем ['@', '?']
            'disabledCommands' => ['netmount'], //отключение ненужных команд https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#commands
            'roots' => [
                [
                    'baseUrl'=>'@web',
                    'basePath'=>'@webroot',
                    'path' => 'files/global',
                    'name' => 'Global'
                ],
                [
                    'class' => 'mihaildev\elfinder\volume\UserPath',
                    'path'  => 'files/user_{id}',
                    'name'  => 'My Documents'
                ],
                [
                    'path' => 'files/some',
                    'name' => ['category' => 'my','message' => 'Some Name'] //перевод Yii::t($category, $message)
                ],
                [
                    'path'   => 'files/some',
                    'name'   => ['category' => 'my','message' => 'Some Name'], // Yii::t($category, $message)
                    'access' => ['read' => '*', 'write' => 'UserFilesAccess'] // * - для всех, иначе проверка доступа в даааном примере все могут видет а редактировать могут пользователи только с правами UserFilesAccess
                ]
            ],
            'watermark' => [
            		'source'         => __DIR__.'/logo.png', // Path to Water mark image
                     'marginRight'    => 5,          // Margin right pixel
                     'marginBottom'   => 5,          // Margin bottom pixel
                     'quality'        => 95,         // JPEG image save quality
                     'transparency'   => 70,         // Water mark image transparency ( other than PNG )
                     'targetType'     => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
                     'targetMinPixel' => 200         // Target image minimum pixel size
            ]
        ]
    ],
'controllerMap' => [
        'elfinder' => [
			'class' => 'mihaildev\elfinder\PathController',
			'access' => ['@'],
			'root' => [
				'path' => 'files',
				'name' => 'Files'
			],
			'watermark' => [
						'source'         => __DIR__.'/logo.png', // Path to Water mark image
						 'marginRight'    => 5,          // Margin right pixel
						 'marginBottom'   => 5,          // Margin bottom pixel
						 'quality'        => 95,         // JPEG image save quality
						 'transparency'   => 70,         // Water mark image transparency ( other than PNG )
						 'targetType'     => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )
						 'targetMinPixel' => 200         // Target image minimum pixel size
			]
		]
    ],

Разница между PathController и Controller в том что PathController работает только с одной папкой также имеет доп возможность передать в запросе на открытие под деритории

На данный момент реализованно использование только LocalFileSystem хранилища (mihaildev\elfinder\volume\Local и mihaildev\elfinder\volume\UserPath) для использования остальных вам прийдётся всё настраивать через mihaildev\elfinder\volume\Base также добавленно расширение https://github.com/MihailDev/yii2-elfinder-flysystem/ это дополнение позволяет интегрировать Flysystem хранилища такие как

Local
Azure
AWS S3 V2
AWS S3 V3
Copy.com
Dropbox
FTP
GridFS
Memory
Null / Test
Rackspace
ReplicateAdapter
SFTP
WebDAV
PHPCR
ZipArchive

Настройка callback-ов для событий

'controllerMap' => [
        'elfinder' => [
            ...            
            'managerOptions' => [
                ...
                'handlers' => [
                    'select' => 'function(event, elfinderInstance) {
                                    console.log(event.data);
                                    console.log(event.data.selected);
                                }', 
                    'open' => 'function(event, elfinderInstance) {...}',
                ],
                ...
            ],
            ...
        ]
    ],

список событий - https://github.com/Studio-42/elFinder/wiki/Client-event-API#event-list

Настройка Плагинов

Изза сложной настройки была переделанна работа плагинов но возможность использовать старые плагины присутствует `php 'controllerMap' => [

    'elfinder' => [
        'class' => 'mihaildev\elfinder\Controller',
        //'plugin' => ['\mihaildev\elfinder\plugin\Sluggable'],
        'plugin' => [
            [
                'class'=>'\mihaildev\elfinder\plugin\Sluggable',
                'lowercase' => true,
                'replacement' => '-'
            ]
         ],
         'roots' => [
                         [
                             'baseUrl'=>'@web',
                             'basePath'=>'@webroot',
                             'path' => 'files/global',
                             'name' => 'Global',
                             'plugin' => [
                                    'Sluggable' => [
                                        'lowercase' => false,
                                    ]
                             ]
                         ],
                     ]

Настройка старого плагина (на примере плагина Sanitizer)
```php
'controllerMap' => [
        'elfinder' => [
            'class' => 'mihaildev\elfinder\Controller',
            'connectOptions' => [
                'bind' => [
                    'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(
                        'Plugin.Sanitizer.cmdPreprocess'
                    ),
                    'ls' => array(
                        'Plugin.Sanitizer.cmdPostprocess'
                    ),
                    'upload.presave' => array(
                        'Plugin.Sanitizer.onUpLoadPreSave'
                    )
                ],
                'plugin' => [
                    'Sanitizer' => array(
                        'enable' => true,
                        'targets'  => array('\\','/',':','*','?','"','<','>','|'), // target chars
                        'replace'  => '_'    // replace to this
                    )
                ],
            ],


             'roots' => [
                             [
                                 'baseUrl'=>'@web',
                                 'basePath'=>'@webroot',
                                 'path' => 'files/global',
                                 'name' => 'Global',
                                 'plugin' => [
                                        'Sanitizer' => array(
                                                                'enable' => true,
                                                                'targets'  => array('\\','/',':','*','?','"','<','>','|'), // target chars
                                                                'replace'  => '_'    // replace to this
                                                            )
                                 ]
                             ],
                         ]

Использование

use mihaildev\elfinder\InputFile;
use mihaildev\elfinder\ElFinder;
use yii\web\JsExpression;

echo InputFile::widget([
    'language'   => 'ru',
    'controller' => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'filter'     => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'name'       => 'myinput',
    'value'      => '',
]);

echo $form->field($model, 'attribute')->widget(InputFile::className(), [
    'language'      => 'ru',
    'controller'    => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'filter'        => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'template'      => '<div class="input-group">{input}<span class="input-group-btn">{button}</span></div>',
    'options'       => ['class' => 'form-control'],
    'buttonOptions' => ['class' => 'btn btn-default'],
    'multiple'      => false       // возможность выбора нескольких файлов
]);

echo ElFinder::widget([
    'language'         => 'ru',
    'controller'       => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'filter'           => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'callbackFunction' => new JsExpression('function(file, id){}') // id - id виджета
]);

Использование при работе с PathController

use mihaildev\elfinder\InputFile;
use mihaildev\elfinder\ElFinder;
use yii\web\JsExpression;

echo InputFile::widget([
    'language'   => 'ru',
    'controller' => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'path' => 'image', // будет открыта папка из настроек контроллера с добавлением указанной под деритории  
    'filter'     => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'name'       => 'myinput',
    'value'      => '',
]);

echo $form->field($model, 'attribute')->widget(InputFile::className(), [
    'language'      => 'ru',
    'controller'    => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'path' => 'image', // будет открыта папка из настроек контроллера с добавлением указанной под деритории 
    'filter'        => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'template'      => '<div class="input-group">{input}<span class="input-group-btn">{button}</span></div>',
    'options'       => ['class' => 'form-control'],
    'buttonOptions' => ['class' => 'btn btn-default'],
    'multiple'      => false       // возможность выбора нескольких файлов
]);

echo ElFinder::widget([
    'language'         => 'ru',
    'controller'       => 'elfinder', // вставляем название контроллера, по умолчанию равен elfinder
    'path' => 'image', // будет открыта папка из настроек контроллера с добавлением указанной под деритории 
    'filter'           => 'image',    // фильтр файлов, можно задать массив фильтров https://github.com/Studio-42/elFinder/wiki/Client-configuration-options#wiki-onlyMimes
    'callbackFunction' => new JsExpression('function(file, id){}') // id - id виджета
]);

CKEditor

use mihaildev\elfinder\ElFinder;

$ckeditorOptions = ElFinder::ckeditorOptions($controller,[/* Some CKEditor Options */]);

Для указания подкаталога (при использовании PathController) `php use mihaildev\elfinder\ElFinder;

$ckeditorOptions = ElFinder::ckeditorOptions([$controller, 'path' => 'some/sub/path'],[/* Some CKEditor Options */]);


Использование совместно с приложением "mihaildev/yii2-ckeditor" (https://github.com/MihailDev/yii2-ckeditor)

```php
use mihaildev\ckeditor\CKEditor;
use mihaildev\elfinder\ElFinder;

$form->field($model, 'attribute')->widget(CKEditor::className(), [
  ...
  'editorOptions' => ElFinder::ckeditorOptions('elfinder',[/* Some CKEditor Options */]),
  ...
]);

Для указания подкаталога (при использовании PathController)

use mihaildev\ckeditor\CKEditor;
use mihaildev\elfinder\ElFinder;

$form->field($model, 'attribute')->widget(CKEditor::className(), [
  ...
  'editorOptions' => ElFinder::ckeditorOptions(['elfinder', 'path' => 'some/sub/path'],[/* Some CKEditor Options */]),
  ...
]);

Проблемы

При встраивание без iframe возможен конфликт с bootstrap.js. Studio-42/elFinder#740 Решение - добавляем в шаблон запись `php

mihaildev\elfinder\Assets::noConflict($this);


## Полезные ссылки

ElFinder Wiki - https://github.com/Studio-42/elFinder/wiki

Flysystem

https://github.com/MihailDev/yii2-elfinder-flysystem/

https://github.com/barryvdh/elfinder-flysystem-driver

https://github.com/creocoder/yii2-flysystem

http://flysystem.thephpleague.com/





[extension] mihaildev/yii2-ckeditor

$
0
0

CKEditor Расширение для Yii 2

  1. Установка
  2. Использование
  3. Полезные ссылки

CKEditor — свободный WYSIWYG-редактор, который может быть использован на веб-страницах.

Установка

Удобнее всего установить это расширение через composer.

Либо запустить

php composer.phar require --prefer-dist mihaildev/yii2-ckeditor "*"

или добавить

"mihaildev/yii2-ckeditor": "*"

в разделе require вашего composer.json файла.

Использование

use mihaildev\ckeditor\CKEditor;
use yii\helpers\Html;

CKEditor::widget([
    'editorOptions' => [
        'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать
        'inline' => false, //по умолчанию false
    ]
]);

//или c ActiveForm

echo $form->field($post, 'content')->widget(CKEditor::className(),[
    'editorOptions' => [
        'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать
        'inline' => false, //по умолчанию false
    ],
]);

Полезные ссылки

CKEditor Api - http://docs.ckeditor.com/

CKEditor Примеры - http://nightly.ckeditor.com/

Файл Менеджер ElFinder - https://github.com/MihailDev/yii2-elfinder

[news] Preparing Yii for the long run

$
0
0
  1. OpenCollective
  2. Goals
  3. Help us to move Yii forward

In order for such a big project as Yii to function properly, we need core contributors watching it constantly: making sure it goes in the right way, managing releases, making decisions. Time proved that while it is possible to do it having a full-time job, it is not as focused, fast and committing as needed.

Previously it was possible to support Yii in many ways: contributing code, participating in community activities, translating documentation. Donating to the project was not among them. The reasons for it were that:

  • We are not the best about paperwork.
  • The idea of how to spend money for the good of the project was very vague.

OpenCollective

An experiment of Alexander Makarov, @samdark, at Patreon proved that many community members find donating the best way to support Yii. The Patreon has drawbacks though. First of all, that's funding of Alexander's work. While the major part of it is Yii, that is not the same as the funding of Yii project overall. Also, Patreon does not provide any transparency regarding spending funds, and we want to make this part clear.

We have found that OpenCollective covers both drawbacks so decided to try it:

  • It allows for supporting the project financially.
  • It handles all the paperwork.
  • There is no need for legal entity (actually we have moved towards e.V. foundation significantly but that is still a huge amount of paperwork, and we would better spend time on what we are good at).
  • It is transparent.

Goals

The funding is collected to make it possible for core team members to work primarily on Yii with minimal or no amount of consulting jobs. The first person willing to try it is Alexander Makarov, @samdark, but others may join later.

Other than that, we may spend funds on our server infrastructure, development tools, design, marketing the framework and other activities and services that move Yii forward.

All that is to:

  • Support Yii 2 releasing new versions of both framework and official extensions.
  • Develop Yii 3 and further major versions. Here is the current roadmap of what is planned.

Help us to move Yii forward

Become Yii backer, starting at $1/month or become an official Yii sponsor, starting at $100/month. All backers and sponsors will be listed in a dedicated page (thanks to OpenCollective we would not forget anyone, they are providing a good API for it).

Become Yii backer or sponsor

The times ahead should be exciting for Yii. Let's make it together!

You may discuss this news on the forum.

[news] Debug extension 2.1.1 released

$
0
0

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

This version fixes some bugs including accessibility ones and adds multiple enhancements:

  • The toolbar is now resizeable. Default height could be set in the configuration.
  • Module pageTitle property added. It allows setting page title to be used.
  • The color contrast of the toolbar was improved.

See the CHANGELOG for details.


[news] Yii 1.1.21 is released

$
0
0

We are very pleased to announce that Yii Framework version 1.1.21 is released. You can download it at yiiframework.com/download/.

This release is a release of Yii 1.1 that has reached maintenance mode and will, only receive necessary security fixes and fixes to adjust the code for compatibility with PHP 7 if they do not cause breaking changes. This allows you to keep your servers PHP version up to date in the environments where old Yii 1.1 applications are hosted and stay within the version ranges supported by the PHP team. Yii 1.1.21 is compatible with PHP 7.3 that, at the time of this writing, has an announced security support until December 6, 2021.

We recommend to use Yii 2.0 for new projects as well as introducing Yii 2.0 for developing new features in existing Yii 1.1 apps, as described in the Yii 2 guide. Upgrading a whole app to Yii 2.0 will, in most cases, result in a total rewrite so this option provides a way for upgrading step by step and allows you to keep old applications up to date even with low budget.

This release includes a few PHP 7 compatibility fixes and security improvements.

For the complete list of changes in this release, please see the change log. For upgrading, always make sure to read the upgrade instructions, however in this release there are no changes that require changes.

We would like to express our gratitude to all contributors who have spent their precious time helping improve Yii and made this release possible.

To comment on this news, you can do so in the related forum post.

[extension] sjaakp/yii2-spatial

$
0
0

Yii2-spatial

  1. Installation
  2. Usage
  3. ActiveRecord method
  4. ActiveQuery method

ActiveRecord with spatial attributes. Those attributes are transformed from the internal MySQL format to GeoJSON format after finding, and vice versa before storing.

Yii-spatial can also be used to find the model or models which are nearest to a given location.

Notice that this extension is intended to be used with a MySQL or MariaDB database exclusively.

Version 1.1.0 is compatible with MySQL 5.7 and MariaDB 10.3.

Installation

Install Yii2-spatial with Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-spatial": "*"

Or run:

composer require sjaakp/yii2-spatial "*"

You can manually install Yii2-spatial by downloading the source in ZIP-format.

Usage

Simply use a sjaakp\spatial\ActiveRecord as base class for your models, like so:

<?php

use sjaakp\spatial\ActiveRecord;

class MySpatialModel extends ActiveRecord
{
    // ...
}

Notice: if you override find() in a sjaakp\spatial\ActiveRecord-derived class, be sure to return a sjaakp\spatial\ActiveQuery and not an 'ordinary' yii\db\ActiveQuery.

ActiveRecord method

featureProperties()
public function featureProperties($field, $geometry)

Override this function to add properties to the GeoJSON encoded attribute.

  • $field is the attribute name.
  • $geometry is an array with the GeoJSON-information, like decoded JSON.

The default implementation adds the ActiveRecord's primary key as the property 'id'.

ActiveQuery method

nearest()
public function nearest($from, $attribute, $radius)

Change the query so that it finds the model(s) nearest to the point given by $from.

  • $from - string|array
    • string: GeoJSON representation of search Point or Feature.
    • array: location in the form [<lng>, <lat>] (two floats).
  • $attribute - string attribute name of Point in the model.
  • $radius - number search radius in kilometers. Default 100.

Example usages:

$here = [4.9, 52.3];     // longitude and latitude of my place

$here2 = '{"type":"Point","coordinates":[4.9,52.3]}';	// another representation
 

$nearestModel = <model>::find()->nearest($here, <attributeName>, 200)->one();    // search radius is 200 km

$fiveNearestModels =  <model>::find()->nearest($here, <attributeName>)->limit(5)->all();	// search radius is 100 km (default)

$dataProvider = new ActiveDataProvider([ 'query' => <model>::find()->nearest($here, <attributeName>) ]);

[extension] sjaakp/yii2-dateline

$
0
0

Yii2 Dateline

  1. Installation
  2. Using Dateline
  3. Bands
  4. Events
  5. Dates
Widget for date-related data in Yii 2.0 PHP Framework.

Dateline widget renders my Javascript jQuery Dateline. The Event data for the dateline are provided by a Yii DataProvider (any object implementing yii\data\DataProviderInterface).

A demonstration of Dateline widget is here.

Installation

Install Dateline with Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-dateline": "*"

Or run:

composer require sjaakp/yii2-dateline "*"

You can manually install Dateline by downloading the source in ZIP-format.

Using Dateline

Yii2-dateline implements a widget of the class Dateline. It gets its data from an ActiveDataProvider, ArrayDataProvider, or other class derived from BaseDataProvider Using it is not unlike using a GridView. For instance, in the Controller you might have something like:

<?php
// ...
public function actionFoo()	{
	$dataProvider = new ActiveDataProvider([
		'query' => InterestingEvent::find(),
	    'pagination' => false
	]);
	
	return $this->render('foo', [
		'dataProvider' => $dataProvider
	]);
}
// ...
?>

An example of rendering a Dateline in the View is:

use sjaakp\dateline\Dateline;

/* ... */

<?php $dl = Dateline::begin([
    'dataProvider' => $dataProvider,
    'attributes' => [
        'id' => 'id',
        'start' => 'date1',
        'text' => 'name'
    ],
    'options' => [
		/* ... */
    ]
]);

$dl->band([
    'size' => '75%',
    'scale' => Dateline::WEEK,
    'interval'=> 90,
])
  ->band([
    'size' => '25%',
    'layout' => 'overview',
    'scale' => Dateline::YEAR,
    'interval'=> 80
]);

Dateline::end();
?>
options

Dateline has the following options:

  • dataProvider: the DataProvider for Dateline. Must be set.
  • attributes: array with key => value pairs of {dateline attribute name} => {model attribute name}. This is used to 'translate' the model attribute names to Dateline attribute names. Required.
  • options: array of options for the underlying Dateline jQuery widget. More information here.
  • htmlOptions (optional): array of HTML options for the Dateline container. Use this if you want to explicitly set the ID.

Bands

Dateline consists of one or more Bands. They each display the Events in a different time resolution.

A Band is defined by the Dateline method band().

public function band( $options )
options

$options is an array with the following keys:

  • size: the part of Dateline occupied by this band, as a percentage or another CSS3 dimension,
  • layout: the only sensible value is 'overview'; all other values (including none) default to 'normal', which is the layout of the main band
  • scale: the time unit that divides the horizontal scale of the Band. The value should be one of the following unit constants (yes, Dateline has an astonishing range!):
    • Dateline::MILLISECOND
    • Dateline::SECOND
    • Dateline::MINUTE
    • Dateline::HOUR
    • Dateline::DAY
    • Dateline::WEEK
    • Dateline::MONTH
    • Dateline::YEAR
    • Dateline::DECADE
    • Dateline::CENTURY
    • Dateline::MILLENNIUM
  • interval: the width of one division on the horizontal scale in pixels
  • multiple (optional): modifies the horizontal scale division to multiples of the unit

Events

Dateline displays Events. These are Models or ActiveRecords characterized by a moment in time.

The Dateline::attributes property holds the translation from Model attribute names to Dateline attribute names.

A few attributes are essential for Dateline. The Dateline names are:

  • start: the point in time where the Event is situated
  • text: the text displayed on main Dateline

Events come in two types:

Instant Events

These are the basic Events, having just one point in time. Dateline displays them as dot icons. Only the above attributes are required.

Duration Events

These have a certain duration. Dateline displays them as a piece of blue 'tape'. Apart from the above, also required is:

  • end: the point in time where, well, the Event ends.

Duration Events also have some optional attributes, making the Event Imprecise:

  • post_start: optional. Indicates a degree of uncertainty in start.

  • pre_stop: optional. Indicates a degree of uncertainty in stop.

The imprecise part of a Duration Event is displayed as faded tape.

Optional Event attribute

Dates

Dateline understands a lot of date formats (in the options and in the Event data). Every date can be provided in one of the following formats:

  • a string, recognized by Javascript Date, that is in RFC2822 or ISO-8601 format; among them MySQL date and datetime fields
  • an integer: Unix time stamp (seconds since the Unix Epoch, 1-1-1970, return value of PHP time())

[extension] jeffersoncarvalho/yii2-quagga

$
0
0

QuaggaJS

  1. Installation
  2. Usage

QuaggaJS

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist jeffersoncarvalho/yii2-quagga "~1.0.2"

or add

"jeffersoncarvalho/yii2-quagga": "~1.0.2"

to the require section of your composer.json file.

Usage

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

PHP `php <?php

use jeffersoncarvalho\quagga\Quagga;

echo Quagga::widget(); 

?>


JavaScript
```javascript
Quagga.onDetected(function(data){
    console.log("Barcode detected and processed : [" + result.codeResult.code + "]", result);
});

[extension] skeeks/yii2-link-activation

$
0
0

Conversion of inactive links in the text

  1. Installation
  2. Client replace (on js)
  3. Backend replace
  4. Screenshot
  5. Video
  6. Links

SkeekS blog

A small extension to convert active links in the text to active (clickable). It can convert html or text, it is possible to convert on the client (js) as well as on the backend (php).

Небольшое расширение для преобразования неактивных ссылок в тексте в активные (кликабельные). Может преобразовывать html или текст, возможно преобразовывать на клиенте (js) а так же на бэкенде (php).

Latest Stable Version Total Downloads

Installation

$ composer require skeeks/yii2-link-activation "^0.0.3"

Or add this to your composer.json file:

{
    "require": {
        "skeeks/yii2-link-activation": "^0.0.3"
    }
}

Client replace (on js)

<?
\skeeks\yii2\linkActivation\assets\TextHandlerAsset::register($this);
$this->registerJs(<<<JS
new sx.classes.LinkActivation(".description");
JS
);
?>
<div class="description">
Какой то текст со ссылками https://test.ru,
https://google.ru/search
Все ссылки будут автоматически https://cms.skeeks.com/blog/releases/2-zapusk-sayta-dlya-skeeks-cms определены в этом тексте и станут кликабельными
</div>

Backend replace

<?
    $handler = new \skeeks\yii2\linkActivation\TextHandler();
    $handler->short_link_max_length = 45;
    echo $handler->replace($yourText);
?>
<?= (new \skeeks\yii2\linkActivation\TextHandler())->replace($yourText); ?>

Screenshot

SkeekS blog

Video

Video

Links

skeeks!
SkeekS CMS (Yii2) — quickly, easily and effectively!
skeeks.com | cms.skeeks.com

[extension] vxm/yii2-mfa

$
0
0

Yii2 MFA

  1. About it
  2. Requirements
  3. Installation
  4. Usage

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality Yii2

About it

An extension support implementing multi factor authenticate base on Spomky-Labs/otphp wrapper for Yii2 user component.

Requirements

Installation

Require Yii2 MFA using Composer:

composer require vxm/yii2-mfa

Usage

App config
'components' => [
    'user' => [
        'as mfa' => [
            'class' => 'vxm\mfa\Behavior',
            'verifyUrl' => 'site/mfa-verify' // verify action, see bellow for setup it
        ]
    ],
]
Identity implementing

When use it, your identity class must be implementing vxm\mfa\IdentityInterface this interface extends from yii\web\IdentityInterface add getMfaSecretKey(), this method return a mfa key of an identity use for generate and validate otp or return null if mfa disabled on an identity.


use yii\db\ActiveRecord;

use vxm\mfa\IdentityInterface;

/**
* @property string $mfa_secret
*/
class User extends ActiveRecord implements IdentityInterface 
{

    public function getMfaSecretKey()
    {
        return $this->mfa_secret;
    }

}


Verify action config

This action use to redirect user when user login and need to be verify mfa otp. Config it in to actions method of your controller


public function actions()
{
    return [
        'mfa-verify' => [
            'class' => 'vxm\mfa\VerifyAction',
            'viewFile' => 'mfa-verify', // the name of view file use to render view. If not set an action id will be use, in this case is `mfa-verify`
            'formVar' => 'model', // the name of variable use to parse [[\vxm\mfa\OtpForm]] object to view file.
            'retry' => true, // allow user retry when type wrong otp
            'successCallback' => [$this, 'mfaPassed'], // callable call when user type valid otp if not set [[yii\web\Controller::goBack()]] will be call.
            'invalidCallback' => [$this, 'mfaOtpInvalid'], // callable call when user type wrong otp if not set and property `retry` is false [[yii\web\User::loginRequired()]] will be call, it should be use for set flash notice to user.
            'retry' => true, // allow user retry when type wrong otp
        ]
    ];
}

After setup verify action, you need create a view (mfa-verify) in this view have a variable model is instance of vxm\mfa\OtpForm use to create a form submit an otp


/**
* @var \vxm\mfa\OtpForm $model
*/

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin();

echo Html::tag('h1', 'Multi factor authenticate');

echo $form->field($model, 'otp');

echo Html::submitButton('Verify');

ActiveForm::end();


QR Code widget for authenticator

After setup all, when user enabled mfa (mfaSecretKey is set) you need to provide a qr code for app like google authenticator to generate an otp. Use vxm\mfa\QrCodeWidget to render a qr code image in view


use vxm\mfa\QrCodeWidget;


echo QrCodeWidget::widget([
    'label' => Yii::$app->user->identity->email,
    'issuer' => Yii::$app->name
]);

authenticator.jpg

Notice: when use this widget ensure user had been logged in, if not an yii\base\InvalidCallException will be throw.

[extension] vxm/yii2-console-menu

$
0
0

Yii2 Console Menu

  1. About it
  2. Requirements
  3. Installation
  4. Usage

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality Yii2

About it

An extension support build pretty menu base on nunomaduro/laravel-console-menu, and is a php-school/cli-menu wrapper for Yii2 console controller.

Requirements

Installation

Require Yii2 console menu using Composer:

composer require vxm/yii2-console-menu

Usage

Quick Setup

demo_0.png


use yii\console\Controller;

/**
 * @method \vxm\consoleMenu\Menu menu(string $title = '', array $options = [])
*/
class TestController extends Controller
{
    /**
     * Execute the action.
     *
     * @return void
     */
    public function actionTest()
    {
        $option = $this->menu('Pizza menu', [
            'Freshly baked muffins',
            'Freshly baked croissants',
            'Turnovers, crumb cake, cinnamon buns, scones',
        ])->open();

        $this->stdout("You have chosen the option number #$option");
    }
}
Setup with a question

demo_1.png


use yii\console\Controller;

/**
 * @method \vxm\consoleMenu\Menu menu(string $title = '', array $options = [])
*/
class TestController extends Controller
{
    /**
     * Execute the action.
     *
     * @return void
     */
    public function actionTest()
    {
        $option = $this->menu('Pizza menu')
                    ->addOption('mozzarella', 'Mozzarella')
                    ->addOption('chicken_parm', 'Chicken Parm')
                    ->addOption('sausage', 'Sausage')
                    ->addQuestion('Make your own', 'Describe your pizza...')
                    ->addOption('burger', 'Prefer burgers')
                    ->setWidth(80)
                    ->open();
        
        $this->stdout("You have chosen the text option: $option");
    }
}
Setup with advanced option, in this case, a password

demo_2.png


use yii\console\Controller;

/**
 * @method \vxm\consoleMenu\Menu menu(string $title = '', array $options = [])
*/
class TestController extends Controller
{
    /**
     * Execute the action.
     *
     * @return void
     */
    public function actionTest()
    {
        $menu = $this->menu('Pizza menu')
                    ->addOption('mozzarella', 'Mozzarella')
                    ->addOption('chicken_parm', 'Chicken Parm')
                    ->addOption('sausage', 'Sausage')
                    ->addQuestion('Make your own', 'Describe your pizza...');
        
        $itemCallable = function (\PhpSchool\CliMenu\CliMenu $cliMenu) use ($menu) {
            $cliMenu->askPassword()
                ->setValidator(function ($password) {
                    return $password === 'secret';
                })
                ->setPromptText('Secret password?')
                ->ask();

            $menu->setResult('Free spice!');

            $cliMenu->close();
        };
        $menu->addItem('Add extra spice for free (password needed)', $itemCallable);


        $option = $menu->addOption('burger', 'Prefer burgers')
            ->setWidth(80)
            ->open();

        $this->stdout("You have chosen the text option: $option");
    }
}
Appearance

Available colors: black, red, green, yellow, blue, magenta, cyan, white.

  $this->menu($title, $options)
      ->setForegroundColour('green')
      ->setBackgroundColour('black')
      ->setWidth(200)
      ->setPadding(10)
      ->setMargin(5)
      ->setExitButtonText("Abort") // remove exit button with ->disableDefaultItems()
      ->setUnselectedMarker('❅')
      ->setSelectedMarker('✏')
      ->setTitleSeparator('*-')
      ->addLineBreak('<3', 2)
      ->addStaticItem('AREA 2')
      ->open();

Check out the full documentation here.


[extension] vxm/yii2-desktop-notifier

$
0
0

Yii2 Desktop Notifier

  1. About it
  2. Requirements
  3. Installation
  4. Usage

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality Yii2

About it

An extension support send desktop notify base on JoliNotif wrapper for Yii2 console controller. Works on Linux, Windows & MacOS.

Requirements

Installation

Require Yii2 desktop notifier using Composer:

composer require vxm/yii2-desktop-notifier

Usage

demo.png


use yii\console\Controller;

/**
 * @method void desktopNotify(string $title, string $body, $icon = null)
 */
class TestController extends Controller
{
    public function actionTest()
    {
        $this->desktopNotify('VXM', 'test message');
    }
}

[extension] huijiewei/yii2-upload

$
0
0

yii2-upload

  1. 安装
  2. 配置及使用
  3. 直传到云存储
  4. 扩展
  5. License

Yii2 下的一个上传组件, 支持直传到第三方云存储。

安装

composer require huijiewei/yii2-upload

配置及使用

本地存储
    // 在 Yii2 components 配置里面增加
    
    'upload' => [
        'class' => \huijiewei\upload\drivers\LocalFile::class,
        'path' => '文件上传的目录',
        'action' => 'site/upload'
    ],
    
    // 根据上面的 action 配置,在对应的控制器里面增加
    
    public function actions()
    {
        return [
            'upload' => [
                'class' => \huijiewei\upload\UploadAction::class,
            ]
        ];
    }
    
    // 使用 widgets 命名空间下的 widget
    
    <?= \huijiewei\upload\widgets\ImageUploadWidget::widget([
        'name' => 'image',
        'value' => '',
    ]) ?>
云存储
    // 阿里云 OSS
    
    'upload' => [
        'class' => \huijiewei\upload\drivers\AliyunOSS::class,
        'accessKeyId' => '',
        'accessKeySecret' => '',
        'endpoint' => '',
        'bucket' => '',
        'folder' => ''
    ],
    
    // 腾讯云 COS
    
     'upload' => [
        'class' => \huijiewei\upload\drivers\TencentCOS::class,
        'appId' => '',
        'secretId' => '',
        'secretKey' => '',
        'bucket' => '',
        'region' => '',
        'folder' => '',
    ],
    
    // 七牛
    
     'upload' => [
        'class' => \huijiewei\upload\drivers\Qiniu::class,
        'accessKey' => '',
        'secretKey' => '',
        'bucket' => '',
        'folder' => '',
        'uploadHost' => '',
        'bucketHost' => '',
        'bucketHttps' => false,
    ],
componentId 自定义

如果想要使用多个存储引擎,可以定义不同的 componentId

然后设置 widget 和 action 的 uploadDriver 属性为对应的 componentId 即可

直传到云存储

该组件支持直传到第三方云存储,实际上就是模拟了表单上传的方式。从流程上来说相比于传统的先上传到服务器,再从服务器传到云存储来说,少了一步转发。从架构上来说,原来的上传都统一走网站服务器,上传量过大时,瓶颈在网站服务器,可能需要扩容网站服务器。采用表单上传后,上传都是直接从客户端发送到云存储。上传量过大时,压力都在云存储上,由云存储来保障服务质量。

目前支持的第三方云储存: 本地(LocalFile) 腾讯云(TencentCOS) 阿里云(AliyunOSS) 七牛(Qiniu) > 其中的本地不算云存储,只是标识仍旧支持本地磁盘存储。

扩展

当然,你也可以拓展支持的云存储,继承 BaseUpload 并实现对应的方法即可

License

MIT

[extension] huijiewei/yii2-wechat

$
0
0

yii2-wechat

  1. 安装
  2. 配置
  3. 配置数据库
  4. 用法

Yii2 微信扩展

本扩展优化了微信网页授权流程

基于 overtrue/wechat.

安装

composer require huijiewei/yii2-wechat

配置

增加 component 配置到 config/main.php:


'components' => [
	// ...
	// componentId 可以自定义多个微信公众号进行配置
	'wechat' => [
		'class' => 'huijiewei\wechat\Wechat',
		// 'appConfig' => [],  # 公众号配置
		// 'paymentConfig' => [],  # 支付配置
		// 'miniProgramConfig' => [],  # 小程序配置
		// 'openPlatformConfig' => [],  # 开放平台配置
		// 'workConfig' => [],  # 企业微信配置
	],
	// ...
]

配置文档

配置数据库

php yii migrate --migrationPath=@vendor/huijiewei/yii2-wechat/src/migrations

用法

微信网页授权:
if(Wechat::getIsWechatClient()) {
    $wechatAuthroize = new WechatAuthorize([
        'wechat' => \Yii::$app->get('wechat')->getApp(),
    ]);
    
    if(!wechatAuthorize()->isAuthorized()) {
        return $wechatAuthorize()->authorizeRequired()->send();
    }
}
JSSDK
WechatShareWidget::widget([
    'wechat' => 'wechat', // componentId, 默认是 wechat
    'shareUrl' => '分享链接',
    'shareIcon' => '分享图标',
    'shareTitle' => '分享标题',
    'shareDescription' => '分享描述',
]);
更多文档

查阅 EasyWeChat 文档.

感谢 overtrue/wechat

[extension] skeeks/yii2-multi-language

$
0
0

Component for multilingual site

  1. Installation
  2. Use config your application
  3. Example
  4. Screenshot
  5. Video
  6. Links

SkeekS blog

Latest Stable Version Total Downloads

Installation

$ composer require skeeks/yii2-multi-language "^1.0.0"

Or add this to your composer.json file:

{
    "require": {
        "skeeks/yii2-multi-language": "^1.0.0"
    }
}

Use config your application


"bootstrap" => ["multiLanguage"],

"language" => "ru", //Your current application language

"components" => [

    "request" => [
        "class" => \skeeks\yii2\multiLanguage\MultiLangRequest::class
    ],
    
    "urlManager" => [
        "class" => \skeeks\yii2\multiLanguage\MultiLangUrlManager::class,
        'enablePrettyUrl' => true,
        'showScriptName' => false,
    ],
    
    "multiLanguage" => [
        "class" => \skeeks\yii2\multiLanguage\MultiLangComponent::class,
        'langs' => ['ru', 'en'],
        'default_lang' => 'ru',         //Language to which no language settings are added.
        'lang_param_name' => 'lang',
    ]
    
]

Example


Url::to(['/module/controller/action', 'id' => 20, 'lang' => 'en'])
// /en/module/controller/action?id=20

Screenshot

SkeekS blog

SkeekS blog

Video

Video

Links

skeeks!
SkeekS CMS (Yii2) — quickly, easily and effectively!
skeeks.com | cms.skeeks.com

[extension] vxm/yii2-searchable

$
0
0

Yii2 Searchable

  1. About it
  2. Requirements
  3. Installation
  4. Configuration
  5. Indexing
  6. Searching

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality Yii2

About it

An extension provide simple full-text search with ideas get from laravel/scout and base on teamtnt/tntsearch wrapper for Yii2 Active Record.

Requirements

Installation

Require Yii2 Searchable using Composer:

composer require vxm/yii2-searchable

Finally, add the \vxm\searchable\SearchableTrait trait and attach vxm\searchable\SearchableBehavior behavior to the active record you would like to make searchable. This will help sync the model with index data

use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;

class Article extends ActiveRecord
{

    use SearchableTrait;

    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return [
            'searchable' => SearchableBehavior::class
        ];
    }


}
Queueing

While not strictly required to use this extension, you should strongly consider configuring a yii2-queue before using an extension. Running a queue worker will allow it to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.

Once you have configured a queue component, set the value of the queue option in your application configuration file to component id of it or an array config of it.

'components' => [
    'searchable' => [
        'class' => 'vxm\searchable\Searchable',
        'queue' => 'queueComponentId'
    ]
]

Configuration

Configuring Component

By default a component will be add to your application components via bootstrapping with id searchable. If you need to config it you can manual config in your application config file:

'components' => [
    'searchable' => [
        'class' => 'vxm\searchable\Searchable',
        'storagePath' => '@runtime/vxm/search',
        'queue' => null, // an optional not required
        'defaultSearchMode' => \vxm\searchable\Searchable::FUZZY_SEARCH,
        'asYouType' => false,
        'fuzziness' => false,
        'fuzzyPrefixLength' => 2,
        'fuzzyMaxExpansions' => 50,
        'fuzzyMaxExpansions' => 50,
        'fuzzyDistance' => 50
    ]
]
Configuring Model Index

Each Active Record model is synced with a given search index, which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model's typical table name. Typically, this is the plural form of the model name; however, you are free to customize the index name by overriding the searchableIndex static method on the Active Record model class:

use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;

class Article extends ActiveRecord
{

    use SearchableTrait;

    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return [
            'searchable' => SearchableBehavior::class
        ];
    }

    /**
     * Get the index name for the model class.
     *
     * @return string
     */
    public static function searchableIndex(): string
    {
        return 'articles_index';
    }

}
Configuring Searchable Data

By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model:

use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;

class Article extends ActiveRecord
{

    use SearchableTrait;

    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return [
            'searchable' => SearchableBehavior::class
        ];
    }

    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray(): array
    {
        $array = $this->toArray();

        // Customize array...

        return $array;
    }

}
Configuring Searchable Key

By default, the primary key name of the model as the unique ID stored in the search index. If you need to customize this behavior, you may override the searchableKey static method on the model:

use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;

class Article extends ActiveRecord
{

    use SearchableTrait;

    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return [
            'searchable' => SearchableBehavior::class
        ];
    }

    /**
     * Get searchable key by default primary key will be use.
     *
     * @return string|int key name.
     */
    public static function searchableKey()
    {
        $array = $this->toArray();

        // Customize array...

        return $array;
    }

}

Indexing

Batch Import

If you are installing an extension into an existing project, you may already have database records you need to import into your search driver. This extension provides an import action that you may use to import all of your existing records into your search indexes:

php yii searchable/import --models="app\models\Post"

You can import multi model classes by separator ,:

php yii searchable/import --models="app\models\Post, app\models\Category"
Adding Records

Once you have added the vxm\searchable\SearchableTrait and attached the vxm\searchable\SearchableBehavior behavior to a model, all you need to do is save a model instance and it will automatically be added to your search index. If you have configured queue this operation will be performed in the background by your queue worker:

$post = new \app\models\Post;

// ...

$post->save();
Adding Via Active Query Result

If you would like to add a Active Query result to your search index, you may use makeSearchable method onto an Active Query result. The makeSearchable method will chunk the results of the query and add the records to your search index. Again, if you have configured queue, all of the chunks will be added in the background by your queue workers:

// Adding via Active Query result...
$models = \app\models\Post::find()->where(['author_id' => 1])->all();

\app\models\Post::makeSearchable($models);

The makeSearchable method can be considered an upsert operation. In other words, if the model record is already in your index, it will be updated. If it does not exist in the search index, it will be added to the index.

Updating Records

To update a searchable model, you only need to update the model instance's properties and save the model to your database. This extension will automatically persist the changes to your search index:

$post = \app\models\Post::findOne(1);

// Update the post...

$post->save();

You may also use the makeSearchable method on an Active Record class to update instance. If the models do not exist in your search index, they will be created:

// Updating via Active Query result...
$models = \app\models\Post::find()->where(['author_id' => 1])->all();

\app\models\Post::makeSearchable($models);
Removing Records

To remove a record from your index, delete the model from the database:

$post = \app\models\Post::findOne(1);

$post->delete();

If you would like to delete a Active Query result from your search index, you may use the deleteSearchable method on an Active Record class:

// Deleting via Active Query result...
$models = \app\models\Post::find()->where(['author_id' => 1])->all();

\app\models\Post::deleteSearchable($models);
Pausing Indexing

Sometimes you may need to perform a batch of Active Record operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch method. This method accepts a single callback which will be immediately executed. Any model operations that occur within the callback will not be synced to the model's index:

\app\models\Post::withoutSyncingToSearch(function () {
   $post = \app\models\Post::findOne(1);
   $post->save(); // will not syncing with index data
});
Conditionally Searchable Model Instances

Sometimes you may need to only make a model searchable under certain conditions. For example, imagine you have app\models\Article model that may be in one of two states: draft and published. You may only want to allow published posts to be searchable. To accomplish this, you may define a shouldBeSearchable method on your model:

use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;

class Article extends ActiveRecord
{

    use SearchableTrait;

    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return [
            'searchable' => SearchableBehavior::class
        ];
    }

    /**
     * Determine if the model should be searchable.
     *
     * @return bool
     */
    public static function shouldBeSearchable()
    {
        return $this->is_published;
    }

}

The shouldBeSearchable method is only applied when manipulating models through the save method. Directly making models using the searchable or makeSearchable method will override the result of the shouldBeSearchable method:

// Will respect "shouldBeSearchable"...
$post = \app\models\Post::findOne(1);

$post->save();

// Will override "shouldBeSearchable"...
$post->searchable();

$models = \app\models\Post::find()->where(['author_id' => 1])->all();

\app\models\Post::makeSearchable($models);

Searching

Simple

You may begin searching a model using the search method. The search method accepts a single string that will be used to search your models. This method return an ActiveQuery you can add more condition or relationship like an origin query.

Note when add more query condition you must not be use where method use andWhere or orWhere instead because it will override search ids condition result.

$posts = \app\models\Post::search('vxm')->all();
$posts = \app\models\Post::search('vxm')->andWhere(['author_id' => 1])->all();


// not use
$posts = \app\models\Post::search('vxm')->where(['author_id' => 1])->all();
Advanced

You can joining relations on search query with relations support searchable:

$posts = \app\models\Post::search('vxm')->joinWith('category')->andWhere(Category::search('vxm category'));
Search mode

You can choice a boolean or fuzzy search mode:

$posts = \app\models\Post::search('vxm', 'fuzzy', ['fuzziness' => true])->all();
$posts = \app\models\Post::search('vxm', 'boolean')->all();

For more detail of search mode please refer to teamtnt/tntsearch to see full document.

Viewing all 3361 articles
Browse latest View live