How to use models in a sub folder in yii1.x

Yii

Posted on 28 May 16 by Vickey
  162

Some times we have two different types of models in our projects for example we have many models and some have prefis 'student' ( student_users ) and some have 'teacher' (teacher_users). So if you want to put these types of models in a different directory you can create a two subdirectory under your model directory and put your models here

 

models

            teacher

            student

Now you need to do some changes in your main.php file under 'protected/config'.  Open main.php file and seacrh  'import'=>'. you will see something like this

'import'=>array(

	'application.models.*',
	'application.components.*',
	'application.widgets.Notification',
	//'ext.yii-mail.YiiMailMessage'
),

change it to

'import'=>array(

	'application.models.student.*',
	'application.models.teacher.*'

	'application.components.*',
	'application.widgets.Notification',
	//'ext.yii-mail.YiiMailMessage'
),

and now can load your models from different locations

How to use ajax pagination in cakephp

Cakephp

Posted on 12 Apr 16 by Vickey
  224

Cakephp provide inbuilt pagination. By using Paginator component we can apply pagination very easily. For example

public $components = array('Paginator');

public function index() {

	$this->Blog->recursive = 0;
	$this->set('users', $this->Paginator->paginate());

}

and in view

<div class="pagination">

echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));

</div>

But when we click on any page number the whole page will be refresh again with new records.  If you dont want to reload page you can fetch all record by using ajax. There is no need to change any code. For load pages by ajax add the below javascript code.

$(document).ready(function(){
   $(".pagination a").click(function(){
        $("#user_list").load(this.href);
         return false;
     })
 });

 

How to install PHP Syntax Checker package in sublime

Others

Posted on 31 Mar 16 by Vickey
  267

Sublime is a light weight and popular text editor. Sublime support many programming languages. In sublime we have highlighted code for each language but by default sublime can not catch the error in your code. If you want to make sure that your code is error free in development process then you need to use Sublime Linter. By using Sublime Linter you can install a package for check any error in your code. You can install this package by following these below steps.

1. Open your sublime text and go to menu >> View >> Show console and paste the below code in sublime console and press Enter

import urllib.request,os,hashlib; h = '2915d1851351e5ee549c20394736b442' + '8bc59f460fa1548d1514676163dafc88';pf = 'Package Control.sublime-package';ipp = sublime.installed_packages_path();urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) );by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read();dh = hashlib.sha256(by).hexdigest();print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

After complete this process a pop up will come. Press OK on pop up.

2. Now Press ctrl + shift + p and you will see a popup

3. In this pop up search 'install package' and click on it and again a popup open

4. Now search 'sublimeLinter-php'  and click on it. After complete process restart sublime Text and now you can catch your error in editor when you type.

How to use queries in pdo way with laravel

Laravel

Posted on 21 Mar 16 by Vickey
  190

Laravel provide us powerful interface for building SQL queries. We can use a query by using table method.

$myRowQuery = DB::table('users');

Laravel provide other method also 

$userData = DB::first('select * from users where id = 1199');

But in some cases we need to use our row query in pdo way. In laravel we can do this very easily. By getting pdo database connection we can use mysql queries in pdo way. Here are some example

Get pdo database conection

$databaseConection 	= 	DB::connection()->getPdo();
$queryStatement = 	$databaseConection->prepare("SHOW TABLES");
$queryStatement->execute();
$tables 	= $queryStatement->fetchAll();

For fetch data from a table

$tables = 	$queryStatement->fetchAll();
$queryStatement = $databaseConection->prepare("select * from users where email = :email");
$queryStatement->execute(array(':email' => "abc@example.com"));
$row = $queryStatement->fetch();

Insert record in a table

$queryStatement = $databaseConection->prepare("insert into users (email) values (:email)");
$queryStatement->execute(array(':email' => 'abc@example.com'));

 

How to use nexmo sms gateway in cakephp

Cakephp

Posted on 09 Mar 16 by Vickey
  343

SMS gateway is used to send text messages from web page to mobile. Many SMS Gateway company provide this functionality by their apis. By using these apis we can send sms from our web pages on a single click. We use this service for send otp and notify our users. There are many SMS Gateway in the market. One of them is nexmo. For using the nexmo apis we need to create an account on nexmo and it provide us api_key and api_secret which used in apis for Authentication. Before start  you need to add and verify your mobile number and a test mobile number. you can add your test mobile number by using this url https://dashboard.nexmo.com/private/settings#test

Here i am using nexmo api with cakephp

First of all we need to download nexmo api SDK from its website. After download  put it in to  'app/vendor' directory and import it in 'AppController'

App::import('Vendor', 'Nexmo', array('file' => 'Nexmo/NexmoMessage.php'));

Now write a function in AppController

protected function _nexmoSendMessage($from = null, $to = null, $text = null)
{
	try {
	
		$url = 'https://rest.nexmo.com/sms/json?';
		$queryParam = array(
			'api_key' => 'api_key',
			'api_secret' => 'api_secret',
			'from' => $from,
			'to' => $to,
			'text' => $text
		);
		$urlQueryString = $url . http_build_query($queryParam);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $urlQueryString);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Receive server response
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		$responseData = curl_exec($ch);
		pr($responseData);
		if (curl_error($ch)) {
			throw new Exception(curl_error($ch));
		}
		curl_close ($ch);
		$data = json_decode($responseData, true);
		if (!isset($data['messages'])) {
			throw new Exception('Unknown API Response.');
		}
		foreach ($data['messages'] as $message) {
			if ($message['status'] != 0) {
				throw new Exception($message['error-text']);
			}
		}
	} catch(Exception $e) {
		CakeLog::write('nexmo_sms_gateway_error_log', $e->getMessage());
	}
}

add your api_key and api_secret

Now use this function in your app where you want send message

public function send(){

	$from='number';
	$to='number';
	$text='Hello';
	$this->_nexmoSendMessage($from, $to, $text);
	die;
}

 

How to use Auth login in cakephp

Cakephp

Posted on 25 Feb 16 by Vickey
  323

Cakephp make our project development very fast. There are many inbuilt functionalities or components. By using these functionalities or functions we can do more in less code if we know about those functionalities very well. Some times we know about the functions or components  but don't know how to use it. For example 'Auth' component. Many new comers in Cakephp don't know how to use it. They make a little mistake and auth login not work properly. Here I will explain and create a simple Auth login in Cakephp.

First of all we need add 'Auth' component in component list. Here I am using it in 'AppController' so that it will work in whole application.

class AppController extends Controller {

	public $components = array('Session','Auth');

}

By default it will use 'User' Model and login fields 'username' and 'password'. But if we are doing some different we can use

public $components = array('Session','Auth' => array(

	'authenticate' => array(

		'Form' => array( 

			'userModel' => 'User',

        	'fields' => array(

                'username' => 'email',
                'password' => 'password'
                
            ),
			#'scope' => array('is_active' => '1')
        )
	),
),
);

By using 'Auth' component we can not access any method with out login. But we need to access login and register actions without logged in. So we can access these by using below code in our controller

public function beforeFilter() {

	parent::beforeFilter();
	$this->Auth->allow('login','register');

} 

Second step Encrypt your password by using AuthComponent. We will save encrypted password in our database table. So we will encrypt it before save in database by using the below code in our Model.

public function beforeSave($options = array()) {
    
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

Now when any user will be register, his password will be save in encrypted form. After register a user we will try to login by using 'Auth' component. For login add the below code in your controller

public function login() {
	
	if($this->request->is('post')){
		if($this->Auth->login()){
			$this->redirect(array('controller'=>'pages','action' => 'home'));
		}
		else
		{
			$this->Session->setFlash(__('Invalid username or password, Please try again.', null),  'default', 
			array('class' => 'errorDisplay'),'login');
		}
	}
}

For logout

public function logout() {
	$this->Auth->logout();
	$this->redirect(array('controller'=>'users', 'action'=>'login'));
}

Now create a login form for login action in 'app/users/login.ctp

<div class="users form">
<?php echo $this->Form->create('User'); ?>
	<fieldset>
		<legend><?php echo __('Login'); ?></legend>
		<?php echo $this->Session->flash('login'); ?>
	<?php
		
		echo $this->Form->input('email');
		echo $this->Form->input('password');
	?>
	</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

Now you can access login page and login by using URL "your base url"/users/login'

How to install and upload source code on Github

Others

Posted on 12 Feb 16 by Vickey
  654

GitHub is the best place where we can share our code with friends and others programmers. It provide us best code management functionality. On GitHub  every developer can share code. Here you can show your skills. On GitHub by using we can control over code version by committing code on Git. GitHub is a web based Git repository hosting service. GitHub is a largest code hosting service. In this tutorial we will install Git and commit code on GitHub step by step. Here I am using Ubuntu operating system.

1. First of all open your terminal and locate in a directory where you want to crate local repository

vickey@vickey-System:~$ cd /home/Desktop

vickey@vickey-System:~/Desktop$

2. Now use the following command to create local repository

vickey@vickey-System:~/Desktop$ git init PHP

when repository created you will see the below line in your terminal

Initialized empty Git repository in /home/vickey/Desktop/PHP/.git/

It will create a new directory with name "PHP"

3. Now change your directory

vickey@vickey-System:~/Desktop$ cd PHP
vickey@vickey-System:~/Desktop/PHP$

4. Here with the below command  create a README file where you will describe about the repository

vickey@vickey-System:~/Desktop/PHP$ gedit README

I used gedit editor you can use other editor. Write your content in the file and save the file

5. This is the important part of this tutorial here we will add our code and files which we will push on GitHub. For now here I am creating a file name as info.php with the below code.

phpinfo();

Now we have two files in "PHP" directory 'README' and 'info.php'

6. Now index these files by using the below commands

vickey@vickey-System:~/Desktop/PHP$ git add README
vickey@vickey-System:~/Desktop/PHP$ git add info.php

This git add command will be used for every file which you have in your directory

7. After files added we will commit these on server

vickey@vickey-System:~/Desktop/PHP$ git commit -m "your message here"

8. Now login your GitHub account and create repository with the name same as you have on your local system. Once you have done run the below command in your terminal. Note that 'vickey' is the GitHub account username please change it first.

vickey@vickey-System:~/Desktop/PHP$ git remote add origin https://github.com/vickey/PHP.git

9. And in last push your code on server

vickey@vickey-System:~/Desktop/PHP$ git push origin master

Username for 'https://github.com': vickey
Password for 'https://vickey@github.com': 
To https://github.com/vickey/PHP.git
 * [new branch]      master -> master

 

How to pass values from Controller to javascript file in Cakephp

Cakephp

Posted on 05 Feb 16 by Vickey
  1099

These days javascript is the essential tool for an internet developer. Every and each internet application uses javascript. Sometimes we need dynamic values from database in js file. For example alert the logedin usename. In simple way we can do this by using the below code

var jsvariable='<?php echo $phpvariable; ?>';

but if you are using cakephp then there is a best way to do this task. In appController.php write the below code

public $helpers = array('Js' => 'Jquery');
public $javascriptVar=array();

public function setJavascriptVariable ($variableName, $variableValue)
{
	if (key_exists($variableName, $this->javascriptVar))
	{
	throw new Exception('a variable already has that name');
	}
	$this->javascriptVar [$variableName] = $variableValue;
}

public function beforeRender()
{
    $this->set('javascriptVariable', $this->javascriptVar);
}

And now by calling the function 'setJavascriptVariable' set javascript values in your controller.

public function welcomePage() {

	$this->setJavascriptVariable('myvar', 'Hi');

}

Now open your layout.ctp file and write the below code

echo $this->Html->scriptBlock('var javascriptVariable = '.$this->Js->object($javascriptVariable).';');

You have done now you can access this variable in every js file

alert(javascriptVariable.myvar);

 

How to change upload max file size value by using htaccess

php

Posted on 03 Feb 16 by Vickey
  908

If you don't have access the php.ini file you can change 'upload_max_filesize','memory_limit','post_max_size' by doing changes in htaccess file if you have the permission to set these values in htaccess file.

php_value memory_limit 80M
php_value post_max_size 50M
php_value upload_max_filesize 30M
php_value upload_max_filesize 10M

For set these value create a .htaccess file on your website root directory ( if not already exist ) and put the code in this file

If you do not have permission to set these values in htaccess then you will get 500 - Internal server error. For solve this you can contact web server support team.

How to get current Controller and current Action name in Laravel

Laravel

Posted on 26 Jan 16 by Vickey
  865

Some times in our projects we need to get current controller or current action name in our code or controller. We can do this in Laravel also by the help of Routing. First of all you need to add the below code at the top in your controller file

use Illuminate\Routing\Route;

Now add this code in your controller class

public $cointrollerName='';
public $actionName='';
public function __construct(Route $route)
{
	$currentAction= $route­>getActionName();
	list($controller, $method) = explode('@', $currentAction);
	$this­>cointrollerName= preg_replace('/.*\\\/', '', $controller);
	$this­>actionName=preg_replace('/.*\\\/', '', $method);
}

and now you can get your controller or action name by using code

	echo $this­>cointrollerName;

	echo $this­>actionName

The complete code will look like this

use Illuminate\Routing\Route;
class ApiController extends Controller
{
	public $cointrollerName='';
	public $actionName='';

	public function __construct(Route $route)
	{
		$currentAction= $route­>getActionName();
		list($controller, $method) = explode('@', $currentAction);
		$this­>cointrollerName= preg_replace('/.*\\\/', '', $controller);
		$this­>actionName=preg_replace('/.*\\\/', '', $method);
	}

	public function index(){

		echo $this­>cointrollerName;
		echo $this­>actionName 
	}

}