Monday, February 8, 2016

Yii 2 Advanced Project Installation

Yii 2 Advanced Project Installation

1. Download Yii2 Advanced from official site:


     i. Go to: http://www.yiiframework.com/download/
         And click on the link  Yii 2 with advanced application template
                                    OR
         Directly visit: https://github.com/yiisoft/yii2/releases/download/2.0.6/yii-advanced-app-2.0.6.tgz

      ii. Now place the extracted folder on your local server's htdocs folder. Say folder name is yii2advanced. In my case using xampp from windows 7. So placed on C:\xampp\htdocs\yii2advanced.

2. Create Database and Connect.
 
    i. Create a empty Database using PHPMyAdmin. Say database name is "yii2advanced".

    ii. Update database details on yii2advanced\common\config\main-local.php.

3. Run init and yii migrate commands.

     i. Go to installed path on your command line tool.
         c:\> cd xampp/htdocs/yii2advanced

     ii.  Run init command.
           c:\xampp\htdocs\yii2advanced>init                 // Select dev / product environment.

     iii. Now run yii migrate on same location.
          c:\xampp\htdocs\yii2advanced>yii migrate

Now you can see the frontend and backend on following urls
Backend:  http://locahost/yii2advanced/backend/web/
Frontend:  http://locahost/yii2advanced/frontend/web/

4. Remove index.php from URL(Enable Pretty URL).
     
Now we are going to remove index.php and query parameters like r=controller/action from URL.

      i. Create .htaccess files in frontend/web and backend/web folders with below codes.
          RewriteEngine on
          # If a directory or a file exists, use it directly
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_FILENAME} !-d
          # Otherwise forward it to index.php
          RewriteRule . index.php

      ii. Add urlManager component inside common/config/main.php as described below.
           'components' => [
        // Your other components.

        'urlManager' => [
                'class' => 'yii\web\UrlManager',
                // Disable index.php
                'showScriptName' => false,
                // Disable r= routes
                'enablePrettyUrl' => true,
                'rules' => array(
      '<controller:\w+>/<id:\d+>' => '<controller>/view',
      '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
      '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ),
         ],
           ],

Now we have to remove front/web from url.
To remove front/web from URL you have to follow Step 5 OR Step 6.

5. Remove frontend/web through .htaccess

i. Create a .htacces file on root direcctory(C:\xampp\htdocs\yii2advanced\) with following lines.

<IfModule mod_rewrite.c> 
  RewriteEngine on

  RewriteCond %{REQUEST_URI} !^public
  RewriteRule ^(.*)$ frontend/web/$1 [L] 
</IfModule>

# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>

# Deny accessing dot files
RewriteRule (^\.|/\.) - [F]

ii. Create a .htacces file on frontend/web(C:\xampp\htdocs\yii2advanced\frontend\web) with following lines.

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php


iii. Update your common config's main.php file(C:\xampp\htdocs\yii2advanced\common\config\main.php) as below

<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
        ],
    ],
];

iv. Update your frontend config's main.php file(C:\xampp\htdocs\yii2advanced\frontend\config\main.php) as below

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
'request' => [
            'baseUrl' => $baseUrl,
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
'urlManager' => [
            'baseUrl' => $baseUrl,
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => []
        ]
    ],
    'params' => $params,
];

All are done, now you can start developing your project.
Now you can see the frontend and backend on following urls
Frontend:  http://locahost/yii2advanced/
Backend:  http://locahost/yii2advanced/backend/web/

6. Remove frontend/web by registering vhost for front and back end.

    i. Open C:\Windows\System32\drivers\etc\hosts.php and add two new urls for your front and backends.

   127.0.0.1       frontend.yii2advanced.com
   127.0.0.1       backend.yii2advanced.com

   ii. Now open C:\xampp\apache\conf\extra\httpd-vhosts.conf file and map locations for above created urls.

<VirtualHost *:80>
   ServerName frontend.yii2advanced.com
   DocumentRoot "C:/xampp/htdocs/advanced_wp/frontend/web/"

   <Directory "C:/xampp/htdocs/advanced_wp/yii-application/frontend/web/">
  # use mod_rewrite for pretty URL support
  RewriteEngine on
  # If a directory or a file exists, use the request directly
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  # Otherwise forward the request to index.php
  RewriteRule . index.php

  # use index.php as index file
  DirectoryIndex index.php

  # ...other settings...
   </Directory>
</VirtualHost>

<VirtualHost *:80>
   ServerName backend.yii2advanced.com
   DocumentRoot "C:/xampp/htdocs/advanced_wp/backend/web/"

   <Directory "D:/xampp/htdocs/advanced_wp/yii-application/frontend/web/">
  # use mod_rewrite for pretty URL support
  RewriteEngine on
  # If a directory or a file exists, use the request directly
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  # Otherwise forward the request to index.php
  RewriteRule . index.php

  # use index.php as index file
  DirectoryIndex index.php

  # ...other settings...
   </Directory>
</VirtualHost>       

Now our site is ready visit front and back end sites on following urls respectively.
http://frontend.yii2advanced.com
http://backend.yii2advanced.com

Wednesday, December 16, 2015

Yii2 DB query using model class

echo $query->createCommand()->sql;
$query->createCommand()->getRawSql()


Add Record:
$model = new Products();
$model->name = 'Light';
$model->color = 'White';
$model->created_date = date('Y-m-d H:m:s');
$model->save();   // Return TRUE or FALSE.
echo $model->id; // Return id for created record.

Update Record:
$model = Products::findOne($id);
$model->name = 'Light';
$model->color = 'White';
$model->created_date = date('Y-m-d H:m:s');
$model->save();   // Return TRUE or FALSE.

Delete Record:
$model = Products::findOne($id);
$model->delete();   // Return TRUE or FALSE;

Products::deleteAll(['color'=>'red']);  // Delete multiple record with condition.

Select Record:
UserEvents::find()->select(['user_events.id', "CONCAT(year, '', month) AS yearmonth", 'location', 'budget_id', 'year', 'month', 'day', 'no_of_guests', 'event_id'])->where(['user_id'=>$bride_id])->andWhere('id != '.$id)->andWhere('"yearmonth" >= :year_month', [':year_month'=>$year_month])->joinWith('budget_master')->joinWith('guest_master')->joinWith('event_type_master')->asArray()->all();

Tuesday, October 27, 2015

Yii2 - Check a record exist

To check a record exist on table use below code,

$exist = User::find()->where(['email' => $email])->exists();

if($exist)
     echo 'Exist.';
else
     echo 'Not exist.';

Wednesday, July 22, 2015

Yii2 Notes

Entry script:
Usually index.php on web folder is entry script. We can change this name. All request to Yii site are executing via Entry Script only. So we can declare here any Constant, Aliases etc.. which are going to use via over all site.

Applications
Applications are objects that govern the overall structure and lifecycle of Yii application systems. Each Yii application system contains a single application object which is created in the entry script and is globally accessible through the expression \Yii::$app.

Application Components
They are the components OR libraries used by Application. Ex: URL Manager.

Aliases (@):
When we not know exact path or URL we can use @ symbol in starting of same, then Yii will search the path or URL through the site. We can also add aliases by manually.

@web will find web directory path of Yii.

Yii::setAlias('@foo', '/path/to/foo'); // Set aliases
Yii::getAlias('@foo/test/file.php');  // Get aliases: /path/to/foo/test/file.php


Class Auto loading:
Yii using PHP's auto loading concept. That is a class will auto load necessary classes when it trying to use them, so we not need to include the necessary class on top. The auto loader is installed when you include the Yii.php file. For this purpose we are using namespace at the top of classes, because namespace having the roots to all classes.

yii\base\Model taking care of form elements and
yii\db\ActiveRecord taking care of database activities.

The expression Yii::$app represents the application instance, which is a globally accessible singleton

Controllers
After Application initiate process Controller will analyze incoming request data, pass them to models, inject model results into views.

Models
Its making control between code and database. Model representing business data, rules and logic.
Attribute: Models represent business data(user inputs and model variables) in terms of attributes.
Attribute Labels: Label of inputs. Ex usage: $model->getAttributeLabel('name'); You may override label of inputs.
Massive Assignment: Assigning post values return back to form when validation fails.
Safe Attributes: Massive assignment only applies to the so-called safe attributes.
Unsafe Attributes: Will used on you may want to validate an attribute but do not want to mark it safe.
Data Exporting: Models often need to be exported in different formats. For example, you may want to convert a collection of models into JSON or Excel format.
Fields: By default, field names are equivalent to attribute names. But you can change it.

Models are the central places to represent business data, rules and logic. They often need to be reused in different places. In a well-designed application, models are usually much fatter than controllers.

Scenarios
A model may be used in different scenarios. For example, a User model may be used to collect user login inputs, but it may also be used for the user registration purpose. In different scenarios, a model may use different business rules and logic. For example, the email attribute may be required during user registration, but not so during user login.








Friday, June 26, 2015

Started to learn Yii 2

I am learning Yii 2 for last 5 days, but I still not get the point. I totally got confused and losing energy, time, confident etc.

I got followings:
1. After my long research I got the point of using "Composer". And learned how to install and use it.
2. Understand url routing.(Like naming controller and functions).
3. Under stand MVC structure which Yii using(Because I already used CodeIgniter).
4. Under stand DB Active Record Queries.

I not got followings:
1. The way of OOPS concept they using is totally making me unhappy. I know oops as middle level. But here they randomly calling function, properties using object OR class. In more case I can't find the function which they called. In that cases I decide that may be default or core.
2. And mainly I am not satisfied with the documents they given(http://www.yiiframework.com/doc-2.0/guide-README.html). They just explained the concept blindly, there is no fully run-able example codes. Just gave the syntax.
3. I cannot understand and implement the login authentication they explained.

As of now I am in 20% only, still I am trying. I hope will get the point in next week. I will post that exp on next week...

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS...