How to Refactor this code

Hi everyone!

is there way to write this code in more efficient way…


<?php

public function actionCreatechitorganization()

    {

        

        $model  = new ChitOrganization();

        $model2 = new ClientUserForm();

        $model3 = new OwnerProfile();

        $countries = Yii::$app->db->createCommand('select * from countries')->queryAll();

		

		if($model->load(Yii::$app->request->post()) &&  $model2->load(Yii::$app->request->post()))

        {

            

            if($model->validate()  &&  $model2->validate())

            {

                

                if(!$model->hasErrors() && !$model2->hasErrors())

                {

                    $model->save();

                    $org_id = Yii::$app->db->lastInsertID;

                    $model2->save($org_id);

                    return $this->render('index');

                   

                }else

                {

                    return $this->render('createorganization', ['model'=>$model, 'model2'=>$model2, 'model3'=>$model3, 'countries'=>$countries]);

                }

            }

            else 

            {

                return $this->render('createorganization', ['model'=>$model, 'model2'=>$model2, 'model3'=>$model3, 'countries'=>$countries]);

            }              

            

        }

        else

        {

            return $this->render('createorganization', ['model'=>$model, 'model2'=>$model2, 'model3'=>$model3, 'countries'=>$countries]);

        }

    }

?>

This is User class I have written is this correct ? :o




<?php


use Yii;

use yii\db\Query;

use yii\web\User as BaseUser;





class ApplicationUser extends BaseUser

{

  

    public function __construct($config = array()) {

       parent::__construct($config);

       

    }

   

    protected function beforeLogin($identity, $cookieBased, $duration) 

    {

        parent::beforeLogin($identity, $cookieBased, $duration);

        return true;    

          

    }

    

    protected function afterLogin($identity, $cookieBased, $duration) 

    {

        parent::afterLogin($identity, $cookieBased, $duration);

        if(!Yii::$app->user->isGuest)

        {

             if(Yii::$app->user->can('organization_owner'))

            {

               Yii::$app->user->setReturnUrl('organization/index');

               ApplicationUser::getClientOrganizationId();

               ApplicationUser::getOrganizationName();

               ApplicationUser::getOrgnizationclientName();

               return true;

               

            }

            else if(Yii::$app->user->can('organization_employee'))

            {

               Yii::$app->user->setReturnUrl('organization/index');

               ApplicationUser::getClientOrganizationId();

               ApplicationUser::getOrganizationName();

               ApplicationUser::getOrgnizationclientName();

               return true;

            }

            else if(Yii::$app->user->can('subscriber'))

            {

                Yii::$app->user->setReturnUrl('subscriber/index');

                return true;

            }

            else if(Yii::$app->user->can('admin'))

            {

                Yii::$app->user->setReturnUrl('admin/index');

                return true;

            }

           

           

        }

    }

   

    protected function beforeLogout($identity) {

       parent::beforeLogout($identity);

       return true;

    }

   

    protected function afterLogout($identity) {

       parent::afterLogout($identity);

       return true;

    }

   

    public static function getClientOrganizationId()

    {

      $organization_qry = new Query();  

      $org_id = $organization_qry->select('organization_id')

                                ->from('manage_client')

                                ->where(['user_id'=>Yii::$app->user->getId()])

                                ->scalar();

      ApplicationUser::setVariableInSession('organization_id', $org_id);

    }

   

    public static function getOrgnizationclientName()

    {

   

       $org_cli_name = new Query();  

       $org_client_name = $org_cli_name->select('name')

                        ->from('manage_client')

                        ->where(['user_id'=>Yii::$app->user->getId()])

                        ->scalar();

      ApplicationUser::setVariableInSession('organization_client_name', $org_client_name);

   

    }

   

    public static function getOrganizationName()

    {

      $org_name = new Query();  

      $organization_name = $org_name->select('org_name')

                        ->from('chit_organization')

                        ->where(['organization_id'=>Yii::$app->session->get('organization_id')])

                        ->scalar();

      ApplicationUser::setVariableInSession('organization_name', $organization_name);

    }

   

    public static function generatePassword($length)

    {

        $sets = [

            'abcdefghjkmnpqrstuvwxyz',

            'ABCDEFGHJKMNPQRSTUVWXYZ',

            '23456789'

        ];

        $all = '';

        $password = '';

        foreach ($sets as $set) {

            $password .= $set[array_rand(str_split($set))];

            $all .= $set;

        }


        $all = str_split($all);

        for ($i = 0; $i < $length - count($sets); $i++) {

            $password .= $all[array_rand($all)];

        }


        $password = str_shuffle($password);


        return $password;

    }

    

    public static function setVariableInSession($key, $value)

    {

       if(!Yii::$app->session->isActive){

           $session = Yii::$app->session;

           $session->open();

       } 

       Yii::$app->session->set($key, $value);

    }

    

    public static function getUserRole($user_id)

    {

        $role_qry = new Query();

        

        $getRole = $role_qry

                   ->select('item_name')

                   ->from('auth_assignment')

                   ->where(['user_id'=>$user_id])

                   ->scalar();

        return $getRole;

        

    }

    

    public static function getOrganizationId($user_id){

       $getOrgId = new Query();

       

       $orgid =$getOrgId

                ->select('organization_id')

                ->from('manage_client')

                ->where(['user_id'=>$user_id])

                ->scalar();

        return $orgid;       

        

    }

    

    public static function isOrganizationBlocked($user_id)

    {

       $orgid = ApplicationUser::getOrganizationId($user_id);

       $isOrgBlocked = new Query();

       $org_status =$isOrgBlocked

                ->select('status_id')

                ->from('chit_organization')

                ->where(['organization_id'=>$orgid])

                ->scalar();

        return $org_status;

        

    }

    

      

    public static function isClientBlocked($user_id)

    {

      

       $isUserBlocked = new Query();

        $isblock =$isUserBlocked

                ->select('status_id')

                ->from('manage_client')

                ->where(['user_id'=>$user_id])

                ->scalar();

        return $isblock;

        

    }

   

   

  

   

   

   

   

   

    

}

Thanks in advance ::)

You can use a "viewmodel" to hide the individual ActiveRecord models from the view. Create a model that extends yii\base\Model and expose all the properties from all the models that you want to input explicitly in the class (not automatically as they work with ActiveRecord models):


class SignupForm extends Model

{

    public $org_display_name;

    public $org_legal_name;

    public $username;

    public $email;

    public $password;

    public $password_repeat;

    public $displayname;

    // etc...

}

In your ‘save’ function, all you need to do is call validate once and then create each ActiveRecord model in turn, populate them from your model properties and then save each of them one after the other. Your function might look something more like this (from my own code):


public function signup()

    {

        if ($this->validate()) {

            $organisation = new Organisation();

            $organisation->display_name = $this->org_display_name;

            $organisation->legal_name = $this->org_legal_name;

            $organisation->save();

            

            $user = new User();

            $user->organisation_id = $organisation->id;

            $user->username = $this->username;

            $user->email = $this->email;

            $user->displayname = $this->displayname;

            $user->setPassword($this->password);

            $user->generateAuthKey();

            $user->save();

            

           

            return $user;

        }


        return null;

    }

Validation will work automatically on "ViewModel" without having to know which but needs to show the error.

you have to make transaction or you may lose data some day