Showing posts with label Yii. Show all posts
Showing posts with label Yii. Show all posts

Thursday 16 January 2014

Error logs save in Db in Yii


1. Yii have its own method to save error logs in DB, follow the steps below in config/main.php Make new db connection (Separate db to save logs)
'log_db'=>array(
          
                        'class'=>'CDbConnection',
                        'connectionString' => 'mysql:host=localhost;dbname=db_name',
                        'emulatePrepare' => true,
                        'username' => 'root',
                        'password' => '',
                        'charset' => 'utf8',
                       
        ),
2. We can use yii default class to save logs in db "CDbLogRoute"
'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                /**/array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                                       
                ),
                // uncomment the following to show log messages on web pages
               
                array(
                    'class'=>'CWebLogRoute',
                ),
                           
                                array(
                    'class'=>'CDbLogRoute',
                             'connectionID'=>'log_db',   
                             'logTableName'=>'yii_logs', //log table name
                             //'categories'=>'error, warning',
                              'levels'=>'error, warning',
                             //'autoCreateLogTable'=>true,
                ),
               
            ),
        ),

3. Yii default table structure to save logs. (It will created automatically if 'autoCreateLogTable'=>true) )
CREATE TABLE IF NOT EXISTS `yii_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` varchar(128) DEFAULT NULL,
  `category` varchar(128) DEFAULT NULL,
  `logtime` int(11) DEFAULT NULL,
  `message` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
Table snapshot with real data
4. You can save custom fields in Yiilog For this you can make your own class and extend to CDbLogRoute (save in protected\components folder) Like this
createCommand()->createTable($tableName, array(
            'id'=>'pk',
            'level'=>'varchar(128)',
            'category'=>'varchar(128)',
            'logtime'=>'integer',
            'message'=>'text',
            'users_id'=>'int(11)',
            'ip'=>'varchar(50)',
            'error_code_id'=>'INT(11)',
            'output_variable'=>'varchar(225)',
            'exception_id'=>'varchar(45)',
                        'exception_category'=>'ENUM("CApplication", "CDbException", "CHttpException", "BException")',
                        'updated_date'=>'timestamp',    
                        'created_date'=>'timestamp',
            
        ));
    }
    

    
    protected function processLogs($logs)
    {

        $command=$this->getDbConnection()->createCommand();
               
                  foreach($logs as $log)
        {
                  $clog  =     explode("::", $log[0]);
                  $elog=CJSON::decode($clog[0]);
                                     
               $command->insert($this->logTableName,array(
                'level'=>$log[1],
                'category'=>$log[2],
                'logtime'=>(int)$log[3],
                'message'=>$log[0],
                                'users_id'=>Yii::app()->user->getId(),
                                'ip'=>Core::getIP(),
                                'error_code_id'=>$elog['error_code_id'],
                                'exception_id'=>$elog['exception_id'],
                                'exception_category'=>$elog['exception_category'],
                                'output_variable'=>$elog['output_variable'],
                                                       
            ));
                      
        }
    }
       



and also some change in main .php
'class'=>'application.components.ELog',
                                        'connectionID'=>'log_db',
                                        //'logTableName'=>'yii_logs',
                                        //'categories'=>'error, warning',
                                       //'levels'=>'error, warning',
                                       'levels'=>'elog',   
                                       'autoCreateLogTable'=>true,
    )

 
In controller you can call it like this
Yii::log(CJSON::encode(array('exception_id'=>00001','error_code_id'=>'1','output_variable'=>'user_id','exception_category'=>'BException'))."::", 'elog');

 

Friday 6 December 2013

Yii vs Magento


Yii Magento
Category Framework Online Shop System
Web application framework

Preference (53% global votes) (43% global votes)
Website www.​yiiframework.​com www.​magentocommerce.​com
License New BSD License OSL 3.0
System requirements
Operating system Cross-platform Cross-platform
Programming language PHP PHP
Memory recommended ? 512 MB
Memory minimum ? 256 MB
More
Description Yii is a high-performance, component-based PHP framework for developing large-scale Web applications rapidly. It enables maximum reusability in Web programming and can significantly accelerate your Web application development process. Magento is a Dynamic & Robust eCommerce Platform
Tag MVC ?
Multi-user system Yes Yes
Autofocus Yes ?
Pingback Yes Yes
Extension/Plug-in Yes Conditional
Interpreter Yes ?
Database MySQL MySQL
SQLite
MSSQL
Oracle
PostgreSQL

Trackback Yes Yes
Multilingual content Yes Yes
Database model Relational Object-relational
Object-oriented

Transactions Yes ?
Unicode Yes Yes
WYSIWYG-Editor Yes Yes
Multiple projects Yes Yes
Standard compliance Yes Yes
External pages Yes No
User statistics Yes Yes
Revision control Yes Yes
Atomicity Yes ?
Isolation Yes ?
Horizontal scalable Yes No
Template language Mustache PHP
drupal
Markdown
Smarty
Twig
PHP

Target audience Beginner Web Development
SMB
Web Development
Cloud computing
Government
App developer
System Adminstration

Framework Yii Zend Framework
Full text search Yes Yes
Scaffolding Yes Yes
Design pattern Active-Record Model-View-Controller
Model-View-Controller
DAO
HMVC
Observer

Development principles Convention over configuration ?
Test-driven development
Don't repeat yourself

Difficulty level Intermediate Intermediate
Application startup time 1 ms 1 m
Version number 1.1.14 1.8
Adobe Flash Support Yes Yes
PSR-0 compliant Yes ?
Object-Relational Mapping (ORM) Yes Yes
Popularity (60% global votes) (67% global votes)
Machine Code Generation Yes Yes
Documentation level ★★★★☆ ★★★☆☆
Multi tasking Yes ?
RESTful Yes Yes
Wastebag Yes ?
Code Generation Yes ?
Dynamic typing Yes Yes
Composite keys Yes ?
Programming paradigm Object-oriented Object-oriented
Event-driven

Comments Yes Yes
Multiple categories Yes Yes
Hierarchical menus Yes Yes
Scripting language support JavaScript Prototype
PHP JavaScript
Free to use Yes Yes
Backend PHP PHP
Active Yes Yes
Database Connection Pooling No Yes
Separate Service Layer Yes ?
Web Flows Yes ?
Heroku Support No ?
Creation Date Jan-08 2008
Community Driven Excellent Basic
Wizard Yes ?
WSDL Yes ?
Reliability ★★★★★ ★★★☆☆
Versioning Good Basic
Custom queries Excellent Basic
Input Widgets Yes ?
Layout Structure Template Yes Yes
File Assets Yes Yes
API Good Good
Compiled language No ?
XML Aware Good Good
Client/Server code reuse Model-View-Controller ?
Batch Processing Yes ?
Cloud platform support Amazon EC2 ?
Amazon S3
digital ocean
ucloud biz
OpenShift
Windows Azure
Linode

Admin Generator Yes Yes
Compiler No ?
Library file size 10 MB ?
API comprehensibility ★★★★☆ ★★☆☆☆
Webmail Yes Yes
Jobs Oportunities ★★★★☆ ★★★★★
Implementation flexibility (49% global votes) (0% global votes)
Out-of-the-box functionality (53% global votes) (25% global votes)
Throttling Yes ?
Bundle system Yes Yes
Annotation Support Yes ?
LDAP Yes No
Query Cache Yes Yes
Realtime Yes ?
Data Security Yes Yes
Community feedback ★★★★★ ★★☆☆☆
Ease of use ★★★★★ ★★★★☆
Malicious Injection Prevention Yes ?
Openshift Paas Support No ?
Copy, Cut and Paste Support Yes ?
Free for commercial use Yes ?
ORM Yes ?
Realtime Server Push Yes Yes
Easy of Use Yes ?
Sexiness 100 101
Open Source Yes Yes
Web Developer Toolbar Yes ?
XQuery Support No ?
Websocket Support No ?
Maven support Yes ?
Resource File Processing Yes ?
Partial Classes Yes ?
Perfomance ★★★★★ ★★★★☆
Database migrations Yes Yes
I like it Yes Yes
Debug Mode Yes Yes
Static Typing Yes ?
Click & Edit in Place / WYSIWYG Yes ?
Autocomplete Code Yes ?
UI framewrok 8 ?
Makes you angry No Yes
Test 3 g ?
Easy to Learn Yes No
Ajax Yes ?
User management Yes ?
ORM Join Support Yes ?
Object-Oriented Views Yes ?
Object Oriented Models Yes ?
Mobile ready Yes ?
ACL Yes ?
Requests per second 851 ?
Operating system server Cross-platform ?
Package Manager Yes ?
Easy Setup Yes ?
Jquery Yes ?
Costanzia Yes ?
Grey 50 m ?
Protein ? 18
Browser support ? Firefox
Internet Explorer
Chrome
Safari


Thursday 28 November 2013

File Upload in Yii

File Upload in Yii For File Upload and Save in Database and in physical folder you can use this code In View
beginWidget('CActiveForm', array(
 'id'=>'files-form',
 'enableAjaxValidation'=>false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),

)); ?>


labelEx($model,'filename'); ?>

error($model,'filename'); ?>

endWidget(); ?>

In controller Create Action
public function actionCreate()
    {
        $model=new files;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

                    
        if(isset($_POST['files']))
        {
                   
          $rnd = rand(0,9999); // use to generate random
            $model->attributes=$_POST['files'];
                        $uploadedFile = CUploadedFile::getInstance($model, 'filename');
                        $fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
              
                    $model->filename = $fileName; 
                     $model->size = $uploadedFile->getSize();  //get size of file
                     $model->file_type = $uploadedFile->getType();  //get type of file                      
                       
            if($model->save()){


            $uploadedFile->saveAs(Yii::app()->basePath.'/../uploads/fiels/'.$fileName); // image will uplode to rootDirectory/uploads/fiels/   
                        $this->redirect(array('view','id'=>$model->id));}
                       
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
you can use this function to convert file size (Bytes) to KB and MB and store in db
/**
 * This function use to format Size Units
 * @param type $bytes
 * @return string
 */
function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return
}

you can write This function in helpers\Core.php file and can call function using this code 

$size=  Core::formatSizeUnits($size); // $size is file size

For File Validation you can use CFileValidator

Monday 18 November 2013

Date Validation in Yii

public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
 array('date_attribute', 'type', 'type' => 'date', 'message' => 'Please enter a valid date', 'dateFormat' => 'yyyy-MM-dd'),

 array('date_attribute', 'isDueDateGreater'), 


          );
    }


also we can check EXPIRY DATE must Greater than START DATE
we can wirte function in our Model and use it in rules

 public function isDueDateGreater($attribute, $params) {
         if( strtotime($this->expiry_date) < strtotime($this->start_date) ){
        $this->addError($attribute, 'Expiry date must be greater than start date.');}
      
}

Monday 14 October 2013

SALT implementation in YII

A salt is a random data string that is used as an input to hash a password. The salt and the password are concatenated and encrypted with a cryptographic hash function and the output is then stored in the database. This method can protect the passwords even when the database security has been compromised.
Below is a short demonstration of SALT implementation in YII.
Here is what you have to do:
Go to your components folder, find and open UserIdentity.php file. Here you have to declare a constant variable for the string length that is going to be your salt. 


const SALT_LENGTH = 10;
Next you have to generate your hash password. You can use any random string as salt or key to generate the password.
Next you have to generate your hash password. You can use any random string as salt or key to generate the password.
//class UserIdentity extends CUserIdentity
public function hashPassword($phrase, $salt = null){
$key = 'Gf;B&yXL|beJUf-K*PPiU{wf|@9K9j5?d+YW}?VAZOS%e2c -:11ii<}ZM?PO!96';
if(is_null($sal))
{ $salt = substr(hash('sha512', $key), 0, self::SALT_LENGTH); }
else
{
$salt = substr($salt, 0, self::SALT_LENGTH);//if salt exists in DB
}

$r = hash('sha512', $salt . $key . $phrase);
return $r;

Next you have to validate your password. The function ValidatePassword would compare the generated salt password with the password stored in the database. For that go to your UserIdentity class, open the file user-identity.php and add the following:
class UserIdentity extends CUserIdentity
public function validatePassword($password, $username, $dbPassword){
   
     return $this->hashPassword($password, $username) === $dbPassword;
   

In the end add this code to your authenticate function. 

$record is object of current user record from db
if(!validatePassword($this->password, $this->username, $record->password))
     {
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
     
     }