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

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

Yii sentry server Extension


Sentry Server Protection

Ace's Sentry Server is a dedicated virus and spam server, designed for businesses that run their own mail server.
It is the perfect tool to stop spam and viruses from getting to your mail server, as all mail to your server is first filtered by Sentry. All mail containing viruses is immediately removed. All suspected spam is placed in a quarantine area where it can be checked before it's deleted after a user-defined period.

 By using this Yii extension you can Log all error and exception to sentry server.

Download yiisentrylog 

Yii sentry log is a component for Yii to send all logging and exception to sentry server instead of showing it on screen or save it on files, especially when you set YII_DEBUG to false, this module based on raven-php by getsentry.

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.');}
      
}

Wednesday 30 October 2013

Useful Wigets for Yii

Ajax request in Yii Framework

Here is the code

In View
$.post('<?php echo Yii::app()->createAbsoluteUrl('controller_name/action_name);?>',{variable_name_in_action :variable_value},function(data)
if(data=='')
                 {
 //do this
}
else{

//do this
}

In Controller

public static function actionAction_name()
{
//you can get varible value here
$variable_name_in_action            =    $_POST['variable_value'];

}



Monday 21 October 2013

Create custom validation rule in Yii framework

In the scenarios where validation rules provided by the Yii framework won’t handle your requirements, you can create custom validation rules. One example is the "authenticate" validation rule provided in "LoginForm" model of Yii blog demo. You can create your own by following these steps.

  1. In rules() method of your model, specify name of your custom validation rule e.g check the validation rule for email
public function rules()
{
 // NOTE: you should only define rules for those attributes that
 // will receive user inputs.
 return array(
  array('service_id, review_date, rating, review', 'required'),
  array('email', 'email'),
  array('email', 'checkEmail','on'=>'guestUser'),   
  array('review', 'safe'),
  // The following rule is used by search().
  // Please remove those attributes that should not be searched.
  array('service_id, user_id,email', 'safe', 'on'=>'search'),
 );
}
 
2. Add a new method in your model with same name as your validation rule. In our case "checkEmail" 
/**
 * @param string the name of the attribute to be validated
 * @param array options specified in the validation rule
 */
public function checkEmail($attribute,$params)
{
 $models = ServiceReviews::model()->findAllByAttributes(array('email' =>$this->email,'service_id'=>$this->service_id));
 if(count($model)>0){
   $this->addError($attribute, 'You have already submitted review for this item');
 }
}
 
Note that the validation method should always have the specified signature.
 
 
3. You can create a single validation methods for multiple fields and in 
that method use a switch statement for "$attribute". You can then use 
"$params" to customize error messages etc. for example. 


>public function rules()
{
 // NOTE: you should only define rules for those attributes that
 // will receive user inputs.
 return array(
  array('service_id, review_date, rating, review', 'required'),
  array('email', 'email'), 
  
  array('email', 'checkUser','message'=>'Test message for email validation'),
  array('user_id', 'checkUser','message'=>'Test message for user_id validation'),

  array('review', 'safe'),
  // The following rule is used by search().
  // Please remove those attributes that should not be searched.
  array('service_id, user_id,email', 'safe', 'on'=>'search'),
 );
}
public function checkUser($attribute,$params)
{
 switch($attribute){
  case "email":
   $models = ServiceReviews::model()->findAllByAttributes(array('email' =>$this->email,'service_id'=>$this->service_id));
   if(count($models)>0){
     $this->addError($attribute, $params['message']);
   }
  break;
  case "user_id":
   if(Yii::app()->user->isGuest){
    $models = ServiceReviews::model()->findAllByAttributes(array('user_id' =>Yii::app()->user->id,'service_id'=>$this->service_id));
    if(count($models)>0){
      $this->addError($attribute, $params['message']);
    }
   }
  break;
 }

}
 
 
 
"$params" argument of validation method is an array containing all the 
key/value pairs provided with the rule in "rules()" method. 

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;
     
     }