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

[news] Auth Client extension 2.2.6 released

$
0
0

We are very pleased to announce the release of Auth Client extension version 2.2.6.

This release adds CacheStateStorage that provides state storage based in cache component.

Additionally, request option for turning off SSL peer verification was removed to make extension more secure by default. It may break your application if server doesn't have root certificates set up correctly so make sure to check upgrade guide.

See the CHANGELOG for details.


[news] Debug extension 2.1.12 released

$
0
0

Debug extension version 2.1.12 was released. This release fixes missing timeline panel tooltips and adds a warning message in DB panel when traceLevel is too low in order for it to collect data.

See the CHANGELOG for details.

[news] Gii extension 2.1.2 released

$
0
0

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

This release fixes issue with RTL naming for foreign keys such as id_user that was causing problems in generated code.

Also, it improves some aspects of generated code. float types are now recognized and generated and annotations for nullable types are now there:

/**
 * @property string|null $car_number
 */

See the CHANGELOG for details.

[news] Smarty extension 2.0.9 released

$
0
0

We are pleased to announce the release of Smarty extension version 2.0.9. In this release {js} function was added allowing to instantiate yii\web\JsExpression:

{js assign='expr' expression='function(){alert('expression');}}'}

[news] MongoDB extension 2.1.9 released

$
0
0

We are very pleased to announce the release of MongoDB extension version 2.1.9 that fixes Collection::dropAllIndexes() error when no indexes were dropped.

[news] Yii 2.0.30

$
0
0

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

Version 2.0.30 is a minor release of Yii 2.0 that fixes a number of bugs.

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.

A complete list of changes can be found in the CHANGELOG.

[extension] yii2-vuejs-frontend

$
0
0

Yii2 Vuejs Frontend

  1. Installation
  2. Usage

Yii2 Vuejs frontend. No more need for pjax and faster rendering.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist lars-t/yii2-vuejs-frontend "*"

or add

"lars-t/yii2-vuejs-frontend": "*"

to the require section of your composer.json file.

Usage

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

Extend your ActiveRecord class class YourClass extends \larst\vuefrontend\VueActiveRecord or for yii2-bootstrap class YourClass extends \larst\vuefrontend\VueBootstrapActiveRecord

Inserting Vue-widget around your forms

<?php
    larst\vuefrontend\Vue::begin(['model'=>$model]);
.... form
    larst\vuefrontend\Vue::end();

    ?>

Set the fieldclass in your form 'fieldClass' => 'larst\vuefrontend\VueActiveField' or for yii2-bootstrap 'fieldClass' => 'larst\vuefrontend\VueBootstrapActiveField'

and let Vue know to use the submithandler within your form 'options' => ['v-on:submit' => new yii\web\JsExpression("submitHandler")]

VeeValidate will be used by default. To disable VeeValidate, set in the inputOptions of your field: 'veeValidate' => false. Set enableClientValidation to false in your form, to disable jquery clientvalidation. All yii2-validators are converted automagically to v-validate if possible (still some work todo here).

example yii form ` $form = ActiveForm::begin([

        'enableClientScript' => false,
        'fieldClass' => 'larst\vuefrontend\VueBootstrapActiveField',
        'options' => ['v-on:submit' => new yii\web\JsExpression("submitHandler")]
]);

In your controller

if (Yii::$app->request->isVuejs) { // when you did not implement VueRequest use: if (Yii::$app->request->headers->get('X-VUEJS', false)) {

$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
return [
    'model' => $model->toVueArray(),                                                  // javascript object for model
    'flashes' => Yii::$app->session->getAllFlashes(),                                 // pass flashes to noty
    'form' => ['action' => \yii\helpers\Url::to(['update', 'id' => $model->id])],     // set form action
    'history' => ['location' => \yii\helpers\Url::to(['update', 'id' => $model->id])] // use pushstate history
];

} `

[extension] karbura/sms-manager

$
0
0

sms-manager

Sms manager est une extension qui permet l'envoi de sms via les passerelles LMT et MTARGET


[wiki] UUID instead of an auto-increment integer for ID with Active Record

$
0
0

I have a dream ... I am happy to join with you today in what will go down in history as the > greatest demonstration of

bad design of Active Record.

I have an API. It's built with a RESTful extension over Active Record, and some endpoints provide PUT methods to upload files. By a REST design we create an entity with POST /video first, and then upload a video file with PUT /video/{id}/data.

How do we get the {id}? The essential solutuion is UUID generated by a client. It allows API application to be stateless and scale it, use master-master replication for databases and feel yourself a modern guy. If you have Postgres — lucky you, feel free to use the built-in UUID data type and close this article. With MySQL the essential solution is insert into users values(unhex(replace(uuid(),'-',''))... MySQL team recommends updating our INSERT queries. With Active Record it is not really possible. For fetching UUIDs it recommends adding a virtual column — this can be used.

If you design the application from ground up, you can use defferent fields for a binary and text representation of UUID, and reference them in different parts of an application, but I am bound to the legacy code.

Adding getId()/setId() won't help - data comes from a client in JSON and fills the model object with a setAttributes() call avoiding generic magic methods.

Here's the hack:

Step 1. Add a private $idText property

use yii\db\ActiveRecord;
class Video extends ActiveRecord
{
    private $idText;

Step 2. Add two validators and a filter

['id','match', 'pattern'=>'/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i'],
// convert UUID from text value to binary and store the text value in a private variable
// this is a workaround for lack of mapping in active record
['id','filter','skipOnError' => true, 'filter' => function($uuid) {
    $this->idText = $uuid;
    return pack("H*", str_replace('-', '', $uuid));
}],
//now let's check if ID is taken
['id','unique','filter' => function(\yii\db\Query $q) {
    $q->where(['id' => $this->getAttribute('id')]);
}],

First rule is a validator for an input. Second rule is a filter preparing UUID to be written in a binary format and keeping the text form for output. Third one is a validator running a query over the binary value generated by a filter.

Note: I wrote $this->getAttribute('id'), $this->id returns a text form.

We can write a query to validate data, not to save it.

Step 3. Add getters

public function __get($name)
{
    return ($name === 'id') ? $this->getId() : parent::__get($name);
}

/**
 * Return UUID in a textual representation
 */
public function getId(): string
{
    if ($this->idText === NULL && $this->getIsNewRecord()){
        //the filter did not convert ID to binary yet, return the data from input
        return $this->getAttribute('id');
    }
    //ID is converted
    return $this->idText ?? $this->getAttribute('id_text');
}

Active Record does not call the getter method if attributes contain the property. It should not be this way, so I return the default component behavior and make ID returned the right way. From the other hand, the first valiator calls $model->id triggering the getter before the UUID is saved to the private property so I need to serve the value from user input.

It is strange to mutate data in a validator, but I found this is the only way. I belive I shouldn't use beforeSave() callback to set the binary value for generating SQL, and return the text value back in afterSave() - supporting this code would be a classic hell like #define true false;.

Step 4. Define the mapping for output

public function fields()
{
    $fields = parent::fields();
    $fields['id'] =function(){return $this->getId();};
    return $fields;
}

This method is used by RESTful serializers to format data when you access your API with GET /video requests.

So, now you can go the generic MySQL way

Step 5. add a virtual column

ALTER TABLE t1 ADD id_text varchar(36) generated always as
 (insert(
    insert(
      insert(
        insert(hex(id_bin),9,0,'-'),
        14,0,'-'),
      19,0,'-'),
    24,0,'-')
 ) virtual;

Step 5. Use Object Relation Mapping in Yii 3 when it's available and write simple mapping instead.

[extension] tomlutzenberger/yii2-googletagmanager

$
0
0

Yii2 GoogleTagManager

  1. Installation
  2. Usage
  3. License

Yii2 Widget for Google Tag Manager

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist tomlutzenberger/yii2-googletagmanager "*"

or add

"tomlutzenberger/yii2-googletagmanager": "*"

to the require section of your composer.json file.

Usage

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

<?= \TomLutzenberger\GoogleTagManager\GoogleTagManager::widget() ?>

You can either add the ID of your container to the params.php

<?php
      
return [
    // ...
    'gtmId' => YII_ENV_PROD ? 'GTM-ASDF123' : '',
];

or pass it directly to the widget:

<?= \TomLutzenberger\GoogleTagManager\GoogleTagManager::widget([
    'gtmId' => 'GTM-ASDF123'
]) ?>

License

This package is published under the MIT License and can be used for any commercial and personal projects.

[extension] karbura/sprintpay-gateway

$
0
0

sprintpay-gateway

Sprintpay Gateway est une extension qui permet les paiements mobile money via sprintpay

[extension] sjaakp/yii2-comus

$
0
0

yii2-comus

  1. Comment Module for Yii2 PHP Framework
  2. Prerequisites
  3. Installation
  4. Basic usage
  5. Permissions
  6. Module options
  7. Comment Options
  8. CommentCount Options
  9. UserComments Options
  10. Events
  11. Internationalization
  12. Override view-files
  13. Module ID
  14. Comus?

Comment Module for Yii2 PHP Framework

Comus is a complete comment module for the Yii 2.0 PHP Framework.

It lets authenticated visitors of a website place comments. The moderator, as well as the administrator of the site can accept or reject comments, either after or before they are submitted. They can also update or delete any comment. Optionally, commenters are allowed to update or delete their own comment.

Comus sports three widgets:

  • Comment Displays a comment block with all the comments issued on a certain model (the subject). Intended to be used in a view file.
  • CommentCount Displays the count of comments issued on a subject. Might be used in an index file.
  • UserComments Displays links to all comments issued by a certain user, on several subjects.

A demonstration of Comus is here.

Prerequisites

Comus relies on Role-Based Access Control (RBAC). Therefore, the authManager application component has to be configured. Comus works with Yii's PhpManager as well as with the DbManager.

Comus assumes that the site uses Bootstrap 4. I suppose that it will work under Bootstrap 3, but it will be a lot less pleasing to the eye.

Comus also assumes that Font Awesome 5.x is available, either the Free or the Pro version. If you're adventurous, you may adapt the icons option of the module to make Comus work with another icon font.

It is strongly advised that the app uses Pretty URLs.

Installation

Install yii2-comus in the usual way with Composer. Add the following to the require section of your composer.json file:

"sjaakp/yii2-comus": "*"

or run:

composer require sjaakp/yii2-comus

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

Module

Comus is a module in the Yii2 framework. It has to be configured in the main configuration file, usually called web.php or main.php in the config directory. Add the following to the configuration array:

<?php
// ...
'modules' => [
    'comment' => [
        'class' => 'sjaakp\comus\Module',
        // several options
    ],
],
// ...

The module has to be bootstrapped. Do this by adding the following to the application configuration array:

<php
// ...
'bootstrap' => [
    'comment',
]
// ...

There probably already is a bootstrap property in your configuration file; just add 'comment' to it.

Important: the module should also be set up in the same way in the console configuration (usually called console.php).

Console commands

To complete the installation, two console commands have to be run. The first will create a database table for the comments:

yii migrate

The migration applied is called sjaakp\comus\migrations\m000000_000000_init.

The second console command is:

yii comus

This will set up a role and several permissions in the RBAC-system.

Basic usage

Say we have a site presenting information about books and about movies. We define ActiveRecords Book and Movie. In the view file for the Book model, we can use the Comment widget like so:

   <?php
   // views/book/view.php
   use sjaakp\comus\Comment;
   
   /* @var app\models\Book $model */
   ?>
   
   <?= $model->title ?>
   <?= $model->author ?>
   // ... more information about $model ...
   
   <?= Comment::widget([
        'model' => $model
   ]) ?>
   

Likewise in the view file for the Movie model.

In the index files we might use the CommentCount widget:

   <?php
   // views/book/index.php
   use sjaakp\comus\CommentCount;
   use yii\grid\GridView;
   
   /* @var yii\db\ActiveDataProvider $dataProvider */
   ?>
   
   <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            'title:text',
            [
                'value' => function ($model, $key, $index, $widget) {
                    return CommentCount::widget([ 'model' => $model ]);
                },
                'format' => 'html'  // CommentCount displays a link
            ],
            // ... more columns ...
        ],
        // ... more options ...
   ]) ?>

The site may also provide in displaying information about registered users. The view file for the User model can use the UserComments widget and may look like this:

   <?php
   // views/user/view.php
   use sjaakp\comus\UserComments;
   
   /* @var app\models\User $user */
   ?>
   
   <?= $user->name ?>
   <?= $user->registeredSince ?>
   // ... more information about $user ...
   
   <?= UserComments::widget([
        'userId' => $user->id
   ]) ?>
   
Comment levels

A comment directly on a subject is said to be of level 0. A comment on such comment is said to be a reply or a comment of level 1. And so on. The maximum level of a comment is settable in the module configuration. Default is 0, meaning that only direct comments are possible. Don't set the maximum level to high, if only because each level indents somewhat.

Notice that if the moderator deletes a comment, all of its replies are deleted as well.

Comment block as seen by guest user

Comment Block

Comments by moderators are distinguished by a light background color. Guest is not able to issue a comment, she should login first.

Comment block as seen by authenticated user

Comment Block

His own comments have a light cyan background color. Hovering over a comment shows a button to issue a reply on it (if maxLevel > 0).

Comment block as seen by moderator

Comment Block

Content of rejected comments is readable. Hovering over a comment shows several buttons to manage it.

Buttons

Buttons

From left to right:

  • accept/reject comment
  • previous/next pending comment
  • update comment
  • delete comment
  • reply to comment

Which buttons appear on hovering above a comment, depends on the permissions of the user, and on the status of the comment.

Permissions

Comus defines a few Permissions. They are:

NameDescription
createCommentIssue a comment
updateCommentUpdate a comment
deleteCommentDelete a comment
updateOwnCommentUpdate self-created comment
deleteOwnCommentDelete self-created comment
manageCommentsAccept or reject comments

One Role is defined: moderator. Associated Permissions are updateComment, deleteComment, and manageComments.

If the site sports a Role admin, the Role moderator is included.

Only moderators are allowed to view the comments overview, on URL:

example.com/comment

From there, they can easily jump to pending records, waiting to be accepted or rejected.

Notice that in the default configuration, Comus allows all authenticated users to create comments, and it's not necessary to explicitly give them permission. The createComment Permission is for scenarios where you want to restrict the allowance to issue comments.

Module options

The Comus module has a range of options. They are set in the application configuration like so:

 <?php
 // ...
 'modules' => [
     'comment' => [
         'class' => 'sjaakp\comus\Module',
         'maxLevel' => 2,
         // ...
         // ... more options ...
     ],
 ],
 // ...
 

The options (most are optional) are:

  • loginUrl string|array Url to the login page of the site in the usual Yii-format. Not optional; must be set.
  • profileUrl array|null|false Url of the profile view. Will be extended with 'id' => <user-id>.
    • array Profile is defined elsewhere on the site. Example: ['/profile/view'].
    • null (default) Uses Comus' builtin light weight profile.
    • false User names will never be presented as a link, just as plain text.
  • maxLevel int Maximum depth of comment. If 0 (default) comments can only be issued directly on the subject, not on another comment
  • orderDescending bool Whether comments are presented in descending order. Default: true.
  • showPending bool whether pending comments are visible. Doesn't effect user with 'manageComments' permission; she can always view pending comments. Default: true.
  • showRejected bool whether rejected comments are visible. Notice that for ordinary users, a message is displayed and the actual contents of the comment are hidden. Doesn't effect user with 'manageComments' permission; she can always view rejected comments and their content. Default: true.
  • showOwn bool Overrides showPending and showRejected for comments created by the user herself. Example: if you want rejected comments to be hidden, except for the user's own comments, set showRejected = false and showOwn = true. Strongly recommended if you set showPending = false; otherwise the user won't see that she has issued a comment and probably try again.
  • datetimeFormat string 'standard' | 'relative' | any value yii\i18n\formatter::datetimeFormat can take. Default is 'standard', which yields a combination of 'relative' and 'short'.
  • viewPermission null | string. RBAC-permission needed to view comments. If null (default): all users can view comments, including guests.
  • createPermission null | string. RBAC-permission needed to create comments. If null (default): all authenticated users can create comments.
  • usernameAttr string | callable. Not optional; must be set. Default: 'name'.
    • string: attribute of username (nickname) in identity class.
    • callable: function($identity) returning username.
  • avatarAttr null | string | callable. Default: null.
    • string: attribute of avatar image in identity class.
    • callable: function($identity) returning avatar image.
    • null: no avatar is shown.
  • maxLength int Maximum length of comment, in characters. Default: 400.
  • truncLength int Maximum length of comment fragment presented in UserComments widget and in the moderator's comment overview, in characters. Default: 80.
  • icons array Presets for a number of icons Comus uses. Default: see source.

Comment Options

The Comment widget has three options:

  • model ActiveRecord The model the comment block is related to.
  • subject string Basically, the relative URL of the view file. Either model or subject must be set, preferably model.
  • options array The HTML options for the surrounding div. Default: [].

CommentCount Options

The CommentCount widget has four options:

  • model ActiveRecord The model the comment count is related to.
  • subject string Basically, the relative URL of the view file. Either model or subject must be set, preferably model.
  • showZero bool Whether the widget should be displayed if there are no comments related to the subject. Default: false.
  • template string HTML template for the output. Default: see source.

UserComments Options

The UserComments widget has two options:

  • userId int The ID of the user who issued the comments.
  • datetimeFormat string 'standard' | 'relative' | any value yii\i18n\formatter::datetimeFormat can take. If not set, it takes the setting of the module. Default is 'short'.

UserComments is derived from Yii's GridView, so it has al the options belonging to that class as well.

Events

Comus doesn't define Events of it's own. However, a Comment is just an ordinary ActiveRecord and you can use it's Events to intercept comment events and inject your own code. Refer to the file 'ComusEvents.php' for a possible approach.

Internationalization

All of Comus' utterances are translatable. The translations are in the 'sjaakp\comus\messages' directory.

You can override Comus' translations by setting the application's message source in the main configuration, like so:

 <?php
 // ...
 'components' => [
     // ... other components ...     
     'i18n' => [
          'translations' => [
               // ... other translations ...
              'comus' => [    // override comus' standard messages
                  'class' => 'yii\i18n\PhpMessageSource',
                  'basePath' => '@app/messages',  // this is a default
                  'sourceLanguage' => 'en-US',    // this as well
              ],
          ],
     ],
     // ... still more components ...
 ]

The translations should be in a file called 'comus.php'.

If you want a single or only a few messages translated and use Comus' translations for the main part, the trick is to set up 'i18n' like above and write your translation file something like:

  <?php
  // app/messages/nl/comus.php
  
  $comusMessages = Yii::getAlias('@sjaakp/comus/messages/nl/comus.php');
  
  return array_merge (require($comusMessages), [
     'Empty' => 'Leeg',   // your preferred translation
  ]);

At the moment, the only language implemented is Dutch. Agreed, it's only the world's 52th language, but it happens to be my native tongue. Please, feel invited to translate Comus in other languages. I'll be more than glad to include them into Comus' next release.

Override view-files

Comus' view files can be overridden. Just set the views setting of the module to something like:

 <?php
 // ...
 'modules' => [
     'comment' => [
         'class' => 'sjaakp\comus\Module',
         'views' => [
              'default' => [    // Comus controller id
                  'user' => <view file>    // action => view
              ]
         ],
         // ...
         // ... more options ...
     ],
 ],
 // ...

<view file> can be of any form yii\web\controller::render() accepts.

Module ID

By default, the Module ID is 'comment'. It is set in the module configuration. If necessary (for instance if there is a conflict with another module or application component), you may set the Module ID to something different. Important: in that case, the moduleId property of the Comment and CommentCount widgets must be set to this new value as well.

Comus?

Comus is the ancient Greek god of festivity and revelry. He is the son of Dionysus and is associated with anarchy and chaos. That, and the fact that his name starts with 'com', to me makes Comus a good name for a comment module.

Comus

[extension] tomlutzenberger/yii2-googleanalytics

$
0
0

Yii2 GoogleAnalytics

  1. Installation
  2. Usage
  3. License

Yii2 Widget for Google Analytics

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist tomlutzenberger/yii2-googleanalytics "*"

or add

"tomlutzenberger/yii2-googleanalytics": "*"

to the require section of your composer.json file.

Usage

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

<?= \TomLutzenberger\GoogleAnalytics\GoogleAnalytics::widget() ?>

You can either add the ID of your container to the params.php

<?php
      
return [
    // ...
    'gaId' => YII_ENV_PROD ? 'UA-1234567-01' : '',
];

or pass it directly to the widget:

<?= \TomLutzenberger\GoogleAnalytics\GoogleAnalytics::widget([
    'gaId' => 'UA-1234567-01'
]) ?>

License

This package is published under the MIT License and can be used for any commercial and personal projects.

[extension] diggindata/yii2-app-basic

$
0
0

87473e79ce8d8b84df2f5a291465d42d?s=100

Yii 2 Basic Project Template

  1. DIRECTORY STRUCTURE
  2. REQUIREMENTS
  3. INSTALLATION
  4. CONFIGURATION
  5. TESTING

Yii 2 Basic Project Template is a skeleton Yii 2 application best for rapidly creating small projects.

This is a fork of the offifcial Yii 2 Basic Project Template.

The template contains the basic features including user login/logout and a contact page. It includes all commonly used configurations that would allow you to focus on adding new features to your application.

These modules are included:

  • raoul2000/yii2-bootswatch-asset: Use Bootswatch theme in your Yii application with minimum effort
  • dektrium/user: Flexible user registration and authentication module for Yii2
  • dektrium/rbac: RBAC management module for Yii2
  • nemmo/yii2-attachments: Extension for file uploading and attaching to the models
  • bizley/migration: Migration generator for Yii 2
  • yii2mod/yii2-settings: Yii2 Settings Module
  • thrieu/yii2-grid-view-state: Save filters from GridView to session, keep the filter state between pages.

Also it contains a Lookups module and CRUD to manage gridview saved filters.

Latest Stable Version Total Downloads Build Status

DIRECTORY STRUCTURE

  assets/             contains assets definition
  commands/           contains console commands (controllers)
  config/             contains application configurations
  controllers/        contains Web controller classes
  data/               contains folders for database backups and uploaded files/attachments
  mail/               contains view files for e-mails
  models/             contains model classes
  modules/            contains application modules, currently that are `backuprestore` and `lookup`
  migrations/         contains database migrations to create tables needed
  myTemplates/        contains gii templates for models and CRUD pages
  rbac/               contains an example rule `Author` 
  runtime/            contains files generated during runtime
  tests/              contains various tests for the basic application
  vendor/             contains dependent 3rd-party packages
  views/              contains view files for the Web application
  web/                contains the entry script and Web resources
  widgets/            contains widhets, currently `Alert` and `GridView`

REQUIREMENTS

The minimum requirement by this project template that your Web server supports PHP 5.4.0.

INSTALLATION

Install via Composer

If you do not have Composer, you may install it by following the instructions at getcomposer.org.

You can then install this project template using the following command:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic

Now you should be able to access the application through the following URL, assuming basic is the directory directly under the Web root.

http://localhost/basic/web/
Install from an Archive File

Extract the archive file downloaded from yiiframework.com to a directory named basic that is directly under the Web root.

Set cookie validation key in config/web.php file to some random secret string:

'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => '<secret random string goes here>',
],

You can then access the application through the following URL:

http://localhost/basic/web/
Install with Docker

Update your vendor packages

docker-compose run --rm php composer update --prefer-dist

Run the installation triggers (creating cookie validation code)

docker-compose run --rm php composer install    

Start the container

docker-compose up -d

You can then access the application through the following URL:

http://127.0.0.1:8000

NOTES:

  • Minimum required Docker engine version 17.04 for development (see Performance tuning for volume mounts)
  • The default configuration uses a host-volume in your home directory .docker-composer for composer caches

CONFIGURATION

TESTING

Tests are located in tests directory. They are developed with Codeception PHP Testing Framework. By default there are 3 test suites:

  • unit
  • functional
  • acceptance

Tests can be executed by running

vendor/bin/codecept run

The command above will execute unit and functional tests. Unit tests are testing the system components, while functional tests are for testing user interaction. Acceptance tests are disabled by default as they require additional setup since they perform testing in real browser.

Running acceptance tests

To execute acceptance tests do the following:

  1. Rename tests/acceptance.suite.yml.example to tests/acceptance.suite.yml to enable suite configuration

  2. Replace codeception/base package in composer.json with codeception/codeception to install full featured version of Codeception

  3. Update dependencies with Composer

    composer update

  4. Download Selenium Server and launch it:

    java -jar ~/selenium-server-standalone-x.xx.x.jar

    In case of using Selenium Server 3.0 with Firefox browser since v48 or Google Chrome since v53 you must download GeckoDriver or ChromeDriver and launch Selenium with it:

    ` # for Firefox java -jar -Dwebdriver.gecko.driver=~/geckodriver ~/selenium-server-standalone-3.xx.x.jar

    # for Google Chrome java -jar -Dwebdriver.chrome.driver=~/chromedriver ~/selenium-server-standalone-3.xx.x.jar `

    As an alternative way you can use already configured Docker container with older versions of Selenium and Firefox:

    docker run --net=host selenium/standalone-firefox:2.53.0

  5. (Optional) Create yii2_basic_tests database and update it by applying migrations if you have them.

    tests/bin/yii migrate
    

    The database configuration can be found at config/test_db.php.

  1. Start web server:

    tests/bin/yii serve

  2. Now you can run all available tests

    # run all available tests
    vendor/bin/codecept run
    
    # run acceptance tests
    vendor/bin/codecept run acceptance
    
    # run only unit and functional tests
    vendor/bin/codecept run unit,functional
    
Code coverage support

By default, code coverage is disabled in codeception.yml configuration file, you should uncomment needed rows to be able to collect code coverage. You can run your tests and collect coverage with the following command:

#collect coverage for all tests
vendor/bin/codecept run -- --coverage-html --coverage-xml

#collect coverage only for unit tests
vendor/bin/codecept run unit -- --coverage-html --coverage-xml

#collect coverage for unit and functional tests
vendor/bin/codecept run functional,unit -- --coverage-html --coverage-xml

You can see code coverage output under the tests/_output directory.

[extension] tomlutzenberger/yii2-smartsupp-chat

$
0
0

Yii2 Smartsupp

  1. Installation
  2. Usage
  3. License

Yii2 Widget for Smartsupp Chat

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist tomlutzenberger/yii2-smartsupp-chat "*"

or add

"tomlutzenberger/yii2-smartsupp-chat": "*"

to the require section of your composer.json file.

Usage

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

<?= \TomLutzenberger\Smartsupp\SmartsuppChat::widget() ?>

You can either add the ID of your container to the params.php

<?php
      
return [
    // ...
    'smartsupp' => 'your_key',
];

or pass it directly to the widget:

<?= \TomLutzenberger\Smartsupp\SmartsuppChat::widget([
    'key' => 'your_key'
]) ?>

To be able to use your own triggers you can do this by setting 2 optional parameters:

<?= \TomLutzenberger\Smartsupp\SmartsuppChat::widget([
    'useCustomOpener' => true,
    'useCustomOpenerMobile' => true,
]) ?>

For more details see:

License

This package is published under the MIT License and can be used for any commercial and personal projects.


[extension] coderius/yii2-hit-counter

$
0
0

Yii2 hit counter extention

  1. About extention
  2. Installation
  3. Usage
  4. In view file past hit counter widget:
  5. Testing

Software License Code Coverage Code Intelligence Status Code Quality CodeFactor Build Status

About extention

This extension allows you to organize the collection of data about website visitors. Data is stored in a database.

What visitor data is collected

Javascript and php are used to get information about visitors:

By Javascript:

  • Detect if client cookie enabled
  • Detect if java enabled
  • Detect if client has totuch device
  • Timezone offset
  • Type connection (like 4g etc.)
  • Current url
  • Referer url
  • Client screen width
  • Client screen height
  • Client color depth
  • Client browser language
  • Client history length
  • Client processor ram

By php:

  • Visitor ip address
  • Visitor user agent
  • Visitor referer url
  • Server name
  • Auth user id
  • Port
  • Cookies http
  • Os
  • Client info
  • Client device type (desctop etc.)
  • Device brand
  • Client device model (if detect)
  • Detect is bot
  • Host by ip
  • Is proxy or vpn
  • Date and time visit

Installation

The preferred way to install this extension is through composer.

First download module . Run the command in the terminal: composer require "coderius/yii2-hit-counter"

or add in composer.json "coderius/yii2-hit-counter": "^1.0" and run composer update

Run migrations in root folder project: php yii migrate/to m190926_110717_hit_counter__table --migrationPath=@coderius/hitCounter/migrations

Usage

Include module in app config file. In advanced template go to common/main.php and set to config array next params:

    $conf = [
        ...
    ];
    
    $conf['modules']['hitCounter'] = [
            'class' => 'coderius\hitCounter\Module',
        ];

    $conf['bootstrap'][] = 'coderius\hitCounter\config\Bootstrap';

In view file past hit counter widget:

<?= \coderius\hitCounter\widgets\hitCounter\HitCounterWidget::widget([]); ?>

Testing

For tests neded test database and tables. Documentation about creating test db is at tests/_app/README.md.

In order to run the tests you need to do the following:

  • Set alias in terminal to phpunit: alias phpunit="/var/www/html/yii2-hit-counter/vendor/bin/phpunit"

  • Go to root folder module 'yii2-hit-counter' in terminal and run tests: phpunit

[extension] coderius/yii2-lightbox2-widget

$
0
0

Lightbox2 widget for Yii2

  1. Installation
  2. Usage

The Lightbox2 widget is a customized lightbox script based on Lightbox. and This widget used to overlay images on top of the current page.

alt text

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require coderius/yii2-lightbox2-widget "@dev"

or add

"coderius/yii2-lightbox2-widget" : "@dev"

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

Usage

  • In view:
use coderius\lightbox2\Lightbox2;

<?= coderius\lightbox2\Lightbox2::widget([
    'clientOptions' => [
        'resizeDuration' => 200,
        'wrapAround' => true,
        
    ]
]); ?>

<a href="<?= Yii::getAlias("@img-web-blog-posts/1/middle/pic.jpg"); ?>" data-lightbox="roadtrip" data-title="some title" data-alt="some alt">
    <!-- Thumbnail picture -->
    <?= Html::img("@img-web-blog-posts/pic.jpg"); ?>
</a>

<a href="<?= Yii::getAlias("@img-web-blog-posts/10/middle/pic2.jpg"); ?>" data-lightbox="roadtrip">
    <!-- Thumbnail picture -->
    <?= Html::img("@img-web-blog-posts/pic2.jpg"); ?>
</a>

<a href="<?= Yii::getAlias("@img-web-blog-posts/11/middle/pic3.jpg"); ?>" data-lightbox="roadtrip">
    <!-- Thumbnail picture -->
    <?= Html::img("@img-web-blog-posts/pic3.jpg"); ?>
</a>

You need set data-lightbox attribute to link and path to image in href attribute. If you wanna to set group images, then put identic names to data-lightbox attribute for each needed link.

*Thumbnail picture, by clicking on which opens the widget is wrapped with a link

Reference to plugin github repository that is used in this widget.

[extension] coderius/yii2-jqcloud2-widget

$
0
0

jQCloud widget for Yii2

  1. jQCloud screenshot:
  2. Installation
  3. Basic usage.
  4. Advanced usage.

The jQCloud widget is a customized jQCloud script based on jQCloud. and This widget used to word clouds and tag clouds that are actually shaped like a cloud.

jQCloud screenshot:

alt text

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require coderius/yii2-jqcloud2-widget "@dev"

or add

"coderius/yii2-jqcloud2-widget" : "@dev"

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

Basic usage.

In view:

use coderius\jqcloud2;

<?= \coderius\jqcloud2\jQCloud::widget([
    'tagOptions' => [
        'style' => 'width:100%; height: 350px; border: 1px solid #ccc;',
    ],
    
    'wordsOptions' => [
        ['text'=>"Lorem",'weight' => 13, 'link' =>"#"],
        ['text'=>"Ipsum",'weight' => 10.5, 'html' => ['title' => "My Title", "class" => "custom-class"], 'link' => ['href' => "http://jquery.com/", 'target' => "_blank"]],
        [
            'text'=>"Dolor",
            'weight' => 9.4, 
            'handlers' => [
                'click' => new \yii\web\JsExpression("
                    function() {
                        alert('You clicked the word !');
                    }
                "),
            ]
        ],
        ['text'=>"Sit",'weight' => 8],
        ['text'=>"Amet",'weight' => 6.2],
        ['text'=>"Consectetur",'weight' => 5],
        ['text'=>"Adipiscing",'weight' => 5],
        ['text'=>"Elit",'weight' => 5],
        ['text'=>"Nam et", 'weight' => 5]
            
    ],
   
]); ?>

Advanced usage.

In view:

use coderius\jqcloud2;

<?= \coderius\jqcloud2\jQCloud::widget([
    'tagOptions' => [
        'style' => 'width:100%; height: 350px; border: 1px solid #ccc;',
//        'id' => 'myid',
        ],
    
    'wordsOptions' => [
        ['text'=>"Lorem",'weight' => 13, 'link' =>"#"],
        ['text'=>"Ipsum",'weight' => 10.5, 'html' => ['title' => "My Title", "class" => "custom-class"], 'link' => ['href' => "http://jquery.com/", 'target' => "_blank"]],
        [
            'text'=>"Dolor",
            'weight' => 9.4, 
            'handlers' => [
                'click' => new \yii\web\JsExpression("
                    function() {
                        alert('You clicked the word !');
                    }
                "),
            ]
        ],
        ['text'=>"Sit",'weight' => 8],
        ['text'=>"Amet",'weight' => 6.2],
        ['text'=>"Consectetur",'weight' => 5],
        ['text'=>"Adipiscing",'weight' => 5],
        ['text'=>"Elit",'weight' => 5],
        ['text'=>"Nam et", 'weight' => 5]
            
    ],
    'cloudOptions' => [
        'delay' => 50,
        'autoResize' => true,
//        'colors' => ["#800026", "#bd0026", "#e31a1c", "#fc4e2a", "#fd8d3c", "#feb24c", "#fed976", "#ffeda0", "#ffffcc"],
        'fontSize' => [
            'from' => 0.1,
            'to' => 0.02
        ]
    ],
    'methods' =>    function($containerId, $words){
                        return new \yii\web\JsExpression("
                            var arr = arr || $words;
                            $('#update-demo').on('click', function(e) {
                                e.preventDefault();
                                arr.splice(0, 1);
                                $('#{$containerId}').jQCloud('update', arr);
                            });
                            
//                            $('#{$containerId}').jQCloud('destroy');

                        ");
                    } 
   
    
]); ?>

More info about options look in: site about jQuery plugin

Reference to plugin github repository that is used in this widget.

[extension] slavkovrn/yii2-ion-rangeslider

$
0
0

IonRangeSlider widget for Yii2 Framework uses Ion.RangeSlider plugin version 2.3.0 for jQuery with pjax support

  1. Installation
  2. Usage

IonRangeSlider widget demo page

The extension uses Ion.RangeSlider plugin version 2.3.0 for jQuery https://github.com/IonDen and makes user interface for changing min,max values of any range with pjax support

IonRangeSlider widget

Installation

The preferred way to install this extension is through composer.

Either run:

composer require slavkovrn/yii2-ion-rangeslider

or add

"slavkovrn/yii2-ion-rangeslider": "*"

to the require section of your composer.json file.

Usage

Set link to extension in your view:

<?php
use slavkovrn\ionrangeslider\IonRangeSliderWidget;
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'username')->widget(IonRangeSliderWidget::class,[
	'min' => 0,
	'max' => 10,
	'from' => 2,
	'to' => 6,
    ]) ?>

    <?= $form->field($model, 'email')->widget(IonRangeSliderWidget::class,[
	'min' => 0,
	'max' => 10,
	'from' => 4,
	'to' => 8,
    ]) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>​

write comments to admin

[extension] mgrechanik/yii2-universal-module-sceleton

$
0
0

Yii2 universal module sceleton

  1. Table of contents
  2. Goal
  3. Installing
  4. What it is about
  5. Using

Русская версия

Table of contents

Goal

This extension gives the structure of the module which:

  1. will be self-sufficient and portable because it holds all his functionality in one place
  2. logically divided at backend and frontend parts
  3. easily connects both to Advanced and Basic application templates
  4. with Basic application template:

    • connects to module section only one time
    • there is functionality of protection to all backend controllers (for admin part of your web site)

Installing

The preferred way to install this extension is through composer.:

Either run composer require --prefer-dist mgrechanik/yii2-universal-module-sceleton

or add "mgrechanik/yii2-universal-module-sceleton" : "^1.0" to the require section of your composer.json

What it is about

  • By default module controllers are being searched automatically in it's `$controllerNamespace`
  • We do not use this functionality but define all our controllers in module's `$controllerMap`
  • But we do this not by `$controllerMap` property explicitly but define backend and frontend controllers separately
  • Module has the mode which is set in config; according to this mode `Controller Map` will have only those controllers who fit the mode:
    • With frontend application of Advanced template we connect our module in `'frontend'` mode
    • With backend application of Advanced template we connect our module in `'backend'` mode
    • With Basic template we can connect our module in two modes described above and also in `'backend and frontend'` mode when both controller types are accessible
  • When module get the request it creates the controller from their map, figuring by it's namespace
    whether it is backend or frontend controller to perform additional set up
  • Module expects the next directory structure:
    Module_directory/
     ui/                                  // User Interface of the module
        controllers/
            backend/                      // Backend controllers like the next:
              AdminDefaultController.php  
              ...
            frontend/                     // Frontend controllers like the next: 
              DefaultController.php       
              ...
        views/                            // Views for corresponding controllers 
            backend/
              admin-default/
            frontend/        
              default/
     Module.php                           // module class
    

Using

1) Generate, or create manually, your module class

2) Inherit your module class from universal module class `php use mgrechanik\yiiuniversalmodule\UniversalModule;

class YourModule extends UniversalModule { ` 3) Now create (or generate) frontend controller

  • Take into consideration that it's `namespaceshould beyourModuleNamespace\ui\controllers\frontend`
  • Create all subdirs needed
  • According to controller it's views will reside in `@yourModuleNamespace/ui/views/frontend/YourControllerName/`
  • We need to define this controller in frontend controller map of this module:
    class YourModule extends UniversalModule
    {
      public $frontendControllers = [
          'default',
      ];
    

    , where `'default'matchyourModuleNamespace\ui\controllers\frontend\DefaultController`.
    When the name and class of controller do not match use next definition form: `'default2' => 'SomeDefaultController'`.

Always when you create new controller do not forget to define it in appropriate controller map of your module.

You are not required to inherit your controller classes from any parent type.

4) Now create (or generate) backend controller

  • Logic is the same with 3), but it's `namespaceshould beyourModuleNamespace\ui\controllers\backend`
  • Define it in module at:
    class YourModule extends UniversalModule
    {
      public $backendControllers = [
          'admin-default',
      ];
    
  • It is handy to prefix backend controller names with Admin, so all backend urls could be set up the way all of them will start with admin/

5) Done, your module is ready, you can connect it to application:

config/main.php: `php

// ...
'modules' => [
    'yourModule' => [
        'class' => 'yourModuleNamespace\YourModule',
        'mode' => 'frontend',
    ],
, do not forget to define - [mode](#mode)

> It is comfortable to connect all such modules at first level of application modules, without nested modules 
> but like a simple list of modules we used to see at admin pages of popular **CMS**s, which also gives short urls.

---

## Module settings <span id="settings"></span>

[Connecting](#setup) module to application we can use next it's properties:

#### ```$mode``` - mode in which this module works
You are required to set up it. [Details](#mode)

#### ```$backendLayout``` - layout for backend controllers
Sets up ```layout``` to module when **backend** controller is requested.  
It is useful for *Basic* application template.

#### ```$frontendControllers``` - frontend controller map
[Details](#fcontroller)

#### ```$backendControllers``` - backend controller map
[Details](#bcontroller)

#### ```$controllerMapAdjustCallback``` - callback for final adjustment of controller map

After module's controller map is generated you can adjust it with this function 
which signature is: ```function($map) { ...; return $map; }```

#### ```$backendControllerConfig``` - **backend** controllers settings
When module [creates](#mknows) **backend** controller it could set up controller with these properties.

It is handy, for example, to restrict access to such controllers using yii filters connected like behaviors.

[Example of using](#example-basic). 

#### ```$frontendControllerConfig``` - **frontend** controllers settings
It is the same like ```$backendControllerConfig```

---

## Example of module's set up with *Basic* application template <span id="example-basic"></span>

Lets suppose that we have two modules we are talking about  - ```example``` and ```omega```.  
Here is working configs to set up these modules:

**config/params.php:**
```php
return [
    'backendLayout' => '//lte/main',
    'backendControllerConfig' => [
        'as backendaccess' => [
            'class' => \yii\filters\AccessControl::class,
            'rules' => [
                [
                    'allow' => true,
                    'ips' => ['54.54.22.44'],
                    'matchCallback' => function ($rule, $action){
                        $user = \Yii::$app->user;
                        return !$user->isGuest &&
                            ($user->id == 1);
                },
                ]
            ],
        ],
    ],	
  
];

At this config we gave permission to "admin pages" only to one user `(id==1)`, with additional check for `ip`.

config/web.php: `php

'components' => [
//...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            'admin/<module:(example|omega)>-<controllersuffix>/<action:\w*>' =>
                '<module>/admin-<controllersuffix>/<action>',
            'admin/<module:(example|omega)>-<controllersuffix>' =>
                '<module>/admin-<controllersuffix>',
        ],
    ],	
],
'modules' => [
    'example' => [
        'class' => 'modules\example\Module',
        'mode' => 'backend and frontend',
        'backendLayout' => $params['backendLayout'],
        'backendControllerConfig' => $params['backendControllerConfig'],
    ],
    'omega' => [
        'class' => 'modules\username1\omega\Module',
        'mode' => 'backend and frontend',
        'backendLayout' => $params['backendLayout'],
        'backendControllerConfig' => $params['backendControllerConfig'],
    ],        
], 

---

## How-to <span id="recipe"></span>

#### Make all admin urls start with ```/admin```  <span id="recipe-admin-url"></span>
Lets see *Basic* application template with two "our" modules connected to it:
```php
    'modules' => [
        'example' => [
            ...
        ],
        'omega' => [
            ...
        ],  

If we followed advice above about naming of backend controllers all of them have names like `Admin...Controller`.
So urls to them will be `example/admin-defaultandomega/admin-default`.
And we want all our admin urls to start with `admin/`.

It is easily achived with the next two `Url Rulesfor yoururlManager`: `php

'urlManager' => [
	'enablePrettyUrl' => true,
	'showScriptName' => false,
	'rules' => [
		'admin/<module:(example|omega)>-<controllersuffix>/<action:\w*>' =>
			'<module>/admin-<controllersuffix>/<action>',
		'admin/<module:(example|omega)>-<controllersuffix>' =>
			'<module>/admin-<controllersuffix>',
	],
],

#### Generating **backend** functionality with Gii CRUD generator   <span id="recipe-crud"></span>

You can easily generate CRUD functionality considering that:
* The ```name``` and the ```namespace``` of the **controller** should be choosen according to [documentation](#bcontroller)
* ```View Path``` should match [directory structure](#dir-structure) the module demands

#### How to connect the module to console application?   <span id="recipe-other-console"></span>

If our module has console commands who reside for example here:

Module_directory/ console/

commands/                // Directory for console commands
  HelloController.php

Module.php `
, then in the console application config this module is connected like:

    'modules' => [
        'example' => [
            'class' => 'modules\example\Module',
            'controllerNamespace' => 'yourModuleNamespace\console\commands',
        ],
    ],
Where to put all other module's functionality?

This module regulates only directory structure described above where only from controllers and views their concrete positions are expected.
When writing the rest of functionality you may follow the next advices:

  • If a component is definitely related only to one part of application - backend or frontend then put it in the corresponding subdirectory
  • If there is no such definite separation put it in the root of his directory

For example for models: ` models/

backend/
  SomeBackendModel.php
frontend/
  SomeFrontendModel.php	  
SomeCommonModel.php  
* Since for all user interface of our module we have already created ```ui/``` subdirectory 
then put **forms** and **widgets** there


Viewing all 2941 articles
Browse latest View live