Sunday, 28 June 2020

GIT Version Control in Cpanel

Now in this modern age, everyone will be working through cloud for their projects. And mostly all will be using Git for cloning, forking projects and do updates. So am just trying explain how we can configure it in a cpanel. When am writing this, Iam of the consideration that, you will be having a valid github account, created your project repository in it.

Mostly We can create Github repositories as public and private. For public repositories, the git cloning will go smooth. But for Private projects we have to do some terminal operations to generate ssh keys for doing it.

STEPS

1) In Your Cpanel You should be having a Terminal Access. Make sure you have , talk with your server administrators for having it. You can create ssh key through interface also, but for this case, you will be needing the terminal.

2) In the Terminal , Just type like this:-

ssh-keygen -t rsa -b 4096 -C "username@domain.com"

Make sure the bit is 4096. and  username you can replace it with your cpanel username and domain.com, replace it with your domain name. 

3)After you run this command, the system will prompt you to enter a passphrase. Do not enter a passphrase, and press Enter to continue.

4)Now key will be generated in the system. so Inorder to make sure that, its generated. run this:-

cat ~/.ssh/id_rsa.pub


5) Now you will get an output like:-

ssh-rsa AAAAB3Nzawhdejsfdjhfgdjgfhjfdghjfhgjhjfdhgdfjhgjudfhgjikgfhgfhgfhfghhgfhgfhgfhgfhhgfhasftfgegdggdgdgd...
Copy this and store it somehere. These is your key.

6) Now we have to register key in Github.  For that go to the repository.click settings. and click on Deploy Keys menu.



7) You will see an Add Deploy Key option like this:-

8)After, clicking you will get a form like this:-


8)In the Title text box, enter a display name for the key.

9)In the Key text box, paste the entire SSH key.

10) If you want to push code from your cPanel account to your GitHub account, select the Allow write access checkbox.

11) Now in your cpanel, Go to GIT version control page. 

12) In the page coming, click on create button shown on the right side:-

13) Now a create page will come like this:-

In Clone  URL, enter the SSH details instead of https. That you can get from :-

repository path you can set to the domain directory u want to clone. and give a repository name for identification. Then click on create. Your repository will be successfuly created.

14) Now you can manage, the repository by visiting the git list.


After syncing..may be sometimes you dont want the connection setting files to upload everytime.. so after adding files to gitignore you can perform a command like:-

git rm -r --cached . && git add . && git commit -am "Remove ignored files"
or step by step
git rm -r --cached . 
git add .
git commit -am "Remove ignored files"

Enjoy Coding :-)



Sunday, 21 June 2020

Laravel 7- A Quick Guide on Basic Operations

Laravel is one of the advanced and popular frameworks in php. Recently laravel released its version 7, so Iam noting some of the main features to check, while doing a basic CRUD projects.

1)ROUTING

In Laravel, the routing rules for application is  written in routes/web.php file. Here in Laravel 2 new types of methods has been introduced put and patch.so lets check how we can use those in routes.

Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

In Practical Cases:-

Route::get('cms/list','CmsController@list');

Here if the request comes for cms/list, it will go to CmsController and run the method list(). And you can see its a get request declared.

Consider If you want to store some data, then you have to call that particular method like:-

Route::post('cms/savepost','CmsController@savepost');

Consider if you want to edit a post, the ids passed will be dynamic. so the route will be like:-

Route::get('cms/edit/{id?}','CmsController@edit');

And in  edit method you can retrieve id as parameter and do the operations.

2) TERMINAL ACCESSS

In Laravel , you can make use of the inbuilt terminal come with that for performing many operations. For this you should have composer installed and configured PHP path. that you can search for how to do that. you can download and install from here:- https://getcomposer.org/

    (1)Creating Laravel Project
          
                 composer create-project --prefer-dist laravel/laravel projectname
          

    (2) For Starting Application 
                      
           php artisan serve

After this you can access your application at: http://127.0.0.1:8000/

   (3) Installing Builtin Authentication Library

           php artisan ui vue --auth

  (4) Syncing the Databases

       php artisan migrate

   (5) Making Controiller
   
      php artisan make:controller Controllername

  
   (6) Making Model
    
       php artisan make:model Modelname

    (7)Clearing Caches
      
 For fast operations, laravel is having a feature to save your config, views and routes in its cache. so sometimes after making changes ,it wont make any effect in your system. may be laravel is picking it from cache folder, so use these commands to clear those configurations.

       php artisan config:clear   - For Clearing config Cache files
       php artisan cache:clear    - For Clearing entire cache folder
       php artisan route:clear    - For Clearing route Cache
       php artisan view:clear     - For Clearing view Cache
       php artisan optimize       - For Optimizing the application
   


3) DEFINING CONTROLLERS

In Laravel Controllers are placed in /app/Http/Controllers/ Folder.

In the top before declaring controller normally these namespaces we will be defining:-

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

For including additional helper files or models You can do like:-

use Illuminate\Support\Facades\Auth;

this is for including the Auth model

For Including a model defined in app folder named Cms.php.you can declare like:-

use App\Cms;

Declaring Controller will be like:-

class CmsController extends Controller
{

}

Define controller extending Controller class included through Name space.


4) DEFINING MODELS

Normally models are placed in app/ folder.

Before declaring model we have to include some namespaces like:-

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

The model will be declared like:-

class Cms extends Model
{

}

We declare class by extending Model class which is included through namespace.

When we use Eloquent ORM, we have to define certain properties in this file:-

    protected $table = 'cms_pages';

Define the table name here

    protected $primaryKey = 'page_id';

Define the tables's primary key with this

    protected $guarded = [];

Normally Laravel needs to specify which fields are allowed for mass saving and all in the attribute protected $fillable. But if you declare $guarded variable to null, then all fields will be eligible for filling. If you want to restict certain features, you can define it in this variable separated by comma.

    public $timestamps = false;

Normally while saving or creating, laravel will always check for fields named created_at and updated_at in databases. If you don't want those fields, just declare $timestamps as false.

5)Usage of Middlewares

In Laravel, they have given a provision to include middleware. I will explain a scenario where we can use it. Suppose we are logged in admin panel and we require every pages inside admin panel to check whether admin is logged in otherwise redirect to login page. So normally in other frameworks, we have to check whether the admin is logged in manually. But here we can do it very easy way using middleware. 

For Authentication we have to first include  

use Illuminate\Support\Facades\Auth;

before the controller declaration. Then in the constructor method, we can put 

public function __construct()
{
    $this->middleware('auth');
}
This will autocheck before calling each functions whether its setted or not. You can do this in routes also for each route calling.But more easier way is this one.


6) LOADING MODELS IN CONTROLLERS

For Loading models in controllers we have to first include it on top of controller page. Normally models are placed in app/ folder. so we can call it like:-

use App\Cms;

If we are writing models inside model folder in App directory, then:-

use App\Models\Cms;

Now we can call the model by just writing like this:-

 $query=Cms::select('*');
 $query->where('page_id','=','1')->get();

This is scenario where we calling direct query functions.

For calling functions defined in models:-

  $cmsmodel = new Cms();
  $cmsmodel->unpublish_record($id);

Here its calling unpublish_record function defined in cms model.

7)LOADING MODELS IN VIEWS

WE can call model functions in views by using this:-

$record= App\Cms::where('page_id',$records->parent)->first();

echo $record->title;

8) GET & POST METHODS ACCESSING

We can check, whether a form is submitted or a value is submitted using:-

  if($request->has('submit')) {

    }

For accessing posted values:-

 $request->input('txtMenuTitle');

For getting this normally we have to include request parameter in function declaring.

public function store(Request $request)
    {

    }

And u have to include  use Illuminate\Http\Request;
in the top of controller file.

9)VALIDATION IN LARAVEL

For validating form we can set rules like:-

 $validatedData = $request->validate([
        'txtMenuTitle' => 'required',
        'txtParent' => 'required',
        'txtTitle' => 'required',
        'txtContent' => 'required',
    ]);

If the form doesn't fill all fields on submission, it will not execute further.

10)PAGINATION IN LARAVEL

For Laravel, we just have to call the paginate method by passing number of records per page. it will automatically do everything for you:-

For eg:-

        $query=Cms::select('*');
        $query->where('status','=','1');

        if($keyword!=''){
            $query->where('title', 'LIKE', "%{$keyword}%");
            $query->orWhere('page_title','LIKE', "%{$keyword}%");
            }
       $records=$query->paginate(10);

Here am Just explaining a scenario case, suppose you want to paginate a list of pages, which will be having keywords search also. we will do like this.We have to pass number of records per page into paginate function. 

In View you just have to put:-

<?php echo $pages->links();?>

So a pagination, which is styled in boostrap will appear.

11) LOADING VIEWS IN THE CONTROLLER FUNCTIONS

You can load views by calling:-

 return view('cms.list', $data);

Here views are stored in resources/app/views folder

So by calling this laravel will pick list.blade.php file stored in cms folder inside views.

12) BLADE TEMPLATING IN LARAVEL

In Laravel view files will be saved as extensions blade.php. This is laravels own templating language.

  i) For Loading css and js

     All Css, js, images are stored in public folder. So inorder to access from it put like:-

  <link rel="stylesheet" href="{{asset('theme')}}/assets/css/bootstrap.min.css" />

Here boostrap.min.css is stored in public/theme/assets/css folder.
You can use same to access all the css, js, image  files stored in public folder.


  2)For accessing Images stored in Uploads folder

<img src="{{ URL::to('/') }}/uploads/image.jpg" width="150px" height="150px"  >

3) Extending a main layout in your view File

 @extends('layouts.main')

Our Theme will be having a normal layout for some pages and its content part will be changing for most pages. so in this case we can define a main layout file in views folder and extend it in our view file. here the view is extending main.blade.php stored in layouts folder in the view folder.

4)Defining Sections  in the layout Files

You can define sections in layout file and include it in the place you want it to appear.  This is used when u want to include a common sidebar. but it have to appear between the dynamic view pages.

so define sections like:-

@section('content')
// Design code here
@endsection

then call yield to display where you want:-

@yield('content')

This you can put in the main layout file, so the section content will be replaced in it while including the same.


5) Including template file

You can also include a theme file into the template using the syntax:-

@include('layouts.messagebar')

Here the messagebar.blade.php defined in the layouts folder will be included.


13) IMAGE UPLOADING IN LARAVEL

There are many functions inbuilt in laravel for managing the image uploads.

if ($request->hasFile('txtFile') && $request->file('txtFile')->isValid()) {

//$request->hasFile('txtFile') -this function checks, whether the //file has been submitted from the form.

//$request->file('txtFile')->isValid()- this function checks, whether //the file submitted is valid.

             //receiving file
            $file = $request->file('txtFile');

          //getting file values
   
            $fileorgname      =   $file->getClientOriginalName();
           $fileextension    =   $file->getClientOriginalExtension();
            $filerealpath     =   $file->getRealPath();
            $filesize         =   $file->getSize();
            $filememetype     =   $file->getMimeType();
              
           // defining allowed extensions
            $allowedextensions=array('jpg','jpeg','png','bmp','gif');
            
            //Checking whether uploaded file extension is matching the allowed extensions
            if (in_array($fileextension,$allowedextensions)) 
            { 
              // Getting the stored name and defining the path uploads in public folder to upload the file
              $imagename = $request->txtFile->store('uploads');  

              $imagename=str_replace('uploads/','',$imagename);
              $destinationPath = 'uploads';
//Storing the file to uploads folder 
              $file->move($destinationPath, $imagename);

            }   
    
          }

14)CRUD OPERATIONS IN LARAVEL

INSERT

$insertdata = array('title'=>$name,'content'=>$content',banner'=>$imagename)
Cms::create($insertdata);

Here already CMs model has been loaded and by initiating Cms model and passing the array to create function, the data will be inserted.

UPDATE

ORM

$insertdata = array('title'=>$name,'content'=>$content',banner'=>$imagename)
Cms::where('page_id',$id)->update($insertdata);

Query Builder

   DB::table('cms_pages')->where('page_id', $id)->update(['published' => 0]);


Here calling cms model and passing id and update array we can update records.


RETRIEVING

We can retrieve a single record or a group of records like this:-

ORM

$record= Cms::where('page_id',$id)->first();

QUERY Builder

For getting all:-         

$rec= DB::table('cms_pages')->get();

For retrieving with condition:- 

$rec=DB::table('cms_pages')->where('level', 1)->get();


DELETING

QUERY Builder  Function

 DB::table('cms_pages')->where('page_id', '=',$list[$i])->delete();


15) SESSIONS and FLASH Messages in Laravel

After saving data, if you want to show success or failure messages, the flash method in  session will be handy. 

we can set a flash variable in session like:-

 $request->session()->flash('msg', 'Selected Items Deleted!!');

We can check, whether that msg variable is set by calling:-

        if ($request->session()->has('msg')) {

       
         }

 For accessing the msg variable we can call like:-

     $data['errormsg']=$request->session()->get('msg');












 





Thursday, 11 June 2020

Uploading Large Size Files to GITHUB through git

In Girhub , there is a limitation as users cannot upload files more than 25 mb. So in this cases we have to upload it through GIT. 
For windows you can download GIT by going to this URL;  https://git-scm.com/download/win.

After installing GIT. Open GIT GUI and create a repository.

Then select the folder where your project is lying

Click on Create, then a window will be opened same like this:-


Click on GIT Bash, You will get a terminal screen .Now we have to go to the github site and copy the repository which we want to commit the updates or upload files. So go the repository and copy the Url like this.







Thursday, 28 May 2020

Basic Things to take care when Upgrading from Codeigniter- 3 to Codeigniter-4

Now a big hurdle for all codeigniter developers around the world is to change their projects from CI-3 to CI-4. Now Codeigniter team has changed there formats and structure in such a way that , developers cannot auto-update just  their versions from 3 to 4. They have to manually edit the code and make changes to the code. . So in this article I am going to explain about some of the basic differences in calling functions between the two versions. Here am giving some examples only. For detailed project code and examples, am going to write another post for that in the coming days. For having a peek overview on the changes have a look into these points explained. iam sure someone will get benefit from this article.

1) Folder Structure

Codeigniter-3 

In codeigniter-3, we have a folder called application, under which all the config, controllers, models, views is placed . In this version codeigniter doesn't restricted us for putting our css, js in any folders. Instead we can place it in any folders in the root and we can access it from our views.

Codeigniter-4

In Codeigniter-4, the application folder has been renamed as app. Now there is a folder called public, in it now we have to put all our css, js and all. Now when we access base_url from the views to access this public folder. This feature, Codeigniter team created mainly for security purpose, so that anything outside the public folder cannot be accessed by intruders. Another thing  in this versionis the usage of too many namespaces. so we can access all folders in root in our models and controllers by defining the namespaces. 

2)Routing

Codeigniter-3

Route File is found in application/config/routes.php

$route['cms/list'] = "cms/list";
Here when request comes for domain.com/cms/list/ it will redirect to CMS controller and run the list method in it.
$route['cms/edit/(:any)'] = "cms/edit/$1";
Here when request comes for domain.com/cms/edit/3 , it will redirect to CMS controller and run edit method in it . then passes $id argument into it.

Codeigniter-4

Route File is Found in app/Config/Routes.php

$routes->add('cms/create/', 'Cms::create');
Here you can see route file configuration is little changed. Here Controller,method is designated as Controller::method format  and another change is you have to mention the submission method. If you see, this is actually a  a add form, so you have to create method for accepting post requests. For post methods, we have to do like adding $routes-> add(). For get method please refer for cms/list down.

$routes->add('cms/edit/(:any)', 'Cms::edit/$1');

Here when the request comes for domain/cms/edit/3 , it will call the CMS controller and execute edit function in it passing the $id as parameter.As edit also is a form, which is submitting post parameters, we have to define it as Post function in the route. so we will add as $routes->add();

$routes->get('cms/list/', 'Cms::list');

This is a list function. It is taking only get arguments. so we will configure it as a get method in the route. So we have to add the rule like $routes->get(). So when request comes for domain.com/cms/list/, it will call the CMS controller and execute the list function defined in it.


3) USING CUSTOM NAMESPACES

This is one of the mighty enhancements done by the Codeigniter community in the new version. AS you know Codeigniter 4 is compatible with php version above 7. so it is utilizing the namespace feature of it abundantly in its new version.

Codeigniter 4

You can define your custom namespaces in app/Config/Autoload.php

If you open that particular file,you can see a array called $psr4. You have to add your namespaces there.

For eg:-

$psr4 = [
'App'         => APPPATH,              
APP_NAMESPACE => APPPATH,             
'Config'      => APPPATH . 'Config',
'IonAuth' => ROOTPATH . 'ion-auth-4',
                       'Admin'   => ROOTPATH . 'ci4-admin',
                       'Myapp'   => ROOTPATH . 'app',
];

You can see in the above configuration, i have defined some namespaces like Ion-Auth, Admin,Myapp .etc. What I am doing is assigning the path of those modules to that name. So I can access the controller,models,views in those folders just by using those static names.

For eg:- If am writing below line in any of my controller:-

echo view('Admin\Views\admin_template\admin_mainheader', $data);

System will identify Admin\ as a namespace and it will replace it with the path defined in namespace. so whatever included in that path will be executed. This gives a large advantage when we design our application.


4) DEFINING CONTROLLERS & MODELS

Codeigniter-3

In Codeigniter 3, we used to define controllers like:-

class Cms extends extends CI_Controller {

}

Controller class was extending CI_Controller Class.

we used to define models like:-

class Cms_model extends CI_model {

}

Model class was extending CI_model.

Codeigniter-4

In CI-4 this scenario is completely different.

In controller we have to define like:-

<?php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Modelname;

class Cms extends Controller {

}

?>

Here we have to include Controllers in the top as namespaces. Also have to include models by defining it like this Use App/Models/Modelname. This place you can make use of the custom namespaces we saw above to include your models.

<?php
namespace App\Models;
use CodeIgniter\Model;

class CmsModel extends Model {
}
?>

Same like controllers, we have to define namespace paths for the models and include them. Here model is going to extend the model class instead of CI_model.

5) LOADING LIBRARIES,HELPERS.etc.

Codeigniter-3

        $this->load->database();       
        $this->load->library(['ion_auth', 'form_validation','pagination']);
        $this->load->helper(['url', 'language','form']);
In the previous version, we were loading database, library, helpers and models like this. Just check below how in the CI-4 version, everything is loading.

Codeigniter-4

     $db = \Config\Database::connect();
    $this->ionAuth    = new \IonAuth\Libraries\IonAuth();
    $this->validation = \Config\Services::validation();
    helper(['form', 'url','string','text']);
    $this->session       = \Config\Services::session();
    $pager = \Config\Services::pager();

Here Everything is loading differently. Just check the differences in both calling methods.

6)LOADING MODELS

Codeigniter-3

$this->load->model('cms_model');
$totalrecords= $this->cms_model->get_allrecord();

this is how model was loading and calling functions in the CI-3 Version. Loading the particular model by calling $this->load(->model() function. then calling particular function defined using $this->modelname function() . Now we will check how this is acheived in Codeigniter-4.

Codeigniter-4

Here we have to first include  path to the Model in top of controller before calling it..

use App\Models\CmsModel;

then to create object for the model. we have to declare like this-

$cmsmodel = new CmsModel();

then for calling the function:-

$totalrecords= $cmsmodel->get_allrecords();

Here you can see we are calling the function by using the object declared above. 


7) GET & POST VARIABLES ACCESSING

Codeigniter-3

Accessing Post variable from form submission
$keyword=   $this->input->post('keyword');
Accessing GET variables
$keyword=   $this->input->get('keyword');

Codeigniter-4

Accessing POST variables
$keyword= $this->request->getPost('keyword');
Accessing GET Variables
$keyword=$this->request->getVar('keyword');

8) FORM VALIDATION RULE SET

Codeigniter-3

  $this->form_validation->set_rules('txtMenuTitle', 'Title', 'trim|required');
  $this->form_validation->set_rules('txtParent', 'Parent', 'trim|required');

Codeigniter-4

  $this->validation->setRule('txtMenuTitle', 'Title', 'trim|required');
  $this->validation->setRule('txtParent', 'Parent', 'trim|required');

If you clearly notice you can see there are some minor changes only. form_validation chnaged to validation and set_rules changed to setRule.


9)PAGINATION

Codeigniter-3
    $searchstring='&keyword='.$keyword;
    $config['base_url'] = $data['urls'].'/auth/cms/list';
    $config['suffix']=$searchstring; // passing the search strings
    $config['total_rows'] = $data['count'];// total count of records fetched
    $config['per_page'] = $per_page_records; //count wanted per page
    $config["uri_segment"] = 2;         
    $config['first_url'] = $config['base_url'] .'?'. $config['suffix'];     
    $config['full_tag_open'] = "<ul class='pagination pull-right no-margin'>";
    $config['full_tag_close'] = '</ul>';
    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';
    $config['cur_tag_open'] = '<li class="active"><a href="#">';
    $config['cur_tag_close'] = '</a></li>';
    $config['prev_tag_open'] = '<li>';
    $config['prev_tag_close'] = '</li>';
    $config['first_tag_open'] = '<li>';
    $config['first_tag_close'] = '</li>';
    $config['last_tag_open'] = '<li>';
    $config['last_tag_close'] = '</li>';
    $config['prev_link'] = '<i class="ace-icon fa fa-angle-double-left"></i>';
    $config['prev_tag_open'] = '<li class="prev">';
    $config['prev_tag_close'] = '</li>';
    $config['next_link'] = '<i class="ace-icon fa fa-angle-double-right"></i>';
    $config['next_tag_open'] = '<li class="next">';
    $config['next_tag_close'] = '</li>';
    $config['use_page_numbers'] = FALSE;
    $config['enable_query_strings'] = TRUE;
    $config['page_query_string'] = TRUE;
    $config['reuse_query_string'] = FALSE;
    $config['attributes'] = array('keyword' =>$keyword);
    $config['attributes']['rel'] = TRUE;

    $this->pagination->initialize($config);// initializing the configs 
    $data['pagelinks']= $this->pagination->create_links();//creating links

Here it was like setting all your configuration into the config variable and then passing it to the initialize function, then the pagination class will be auto creating links for you which you will call in the view. Also please note that you can pass the search variables through suffix variable in the config.

Codeigniter-4

 if($keyword!=''){
         $cmsmodel->like('title',$keyword);
         $cmsmodel->orlike('page_title',$keyword);
       }
       
        $data['records']=$cmsmodel->paginate($per_page_records);
        $data['pager']=$cmsmodel->pager;

Here they removed the $config settings procedure. here we just have to call the paginate method on the particular model. Search parameters you can pass just like data fetching way. If you have more search parameters, you just have to append it in the $model->where() or $model->like type of functions. Now in the view you just have to call like:-

<?php  echo $pager->links(); ?>

This will display all the pagination links in the view page. You can further customize these links or pagination style using advanced ci-4 functions codeigniter is providing. Just refer their documentation for more details.

10) CALLING MODEL FUNCTIONS IN VIEWS

Codeigniter-3

<?php
$ci =&get_instance();
$ci->load->model('cms_model');
$record=  $ci->cms_model->getdetails($id);
?>

Sometimes we will be having requirement to call a particular Model function inside view itself. In those scenarios we can call that method in the view using instance function as described above

Codeigniter-4

In CI-4, its is more simple we have to just create an object in the controller method and just pass the object to the view. From there, we can call that particular method from model using the object.

So In Controller define like:-
<?php
 $cmsmodel = new CmsModel();
$data['cmsmodel']=$cmsmodel;
?>
Pass it to the view. then in View, just call the function.
<?php
  $record=  $cmsmodel->getdetails($id); 
?>

11) LOADING VIEWS IN THE CONTROLLER FUNCTIONS

Codeigniter-3

$this->load->view('cms/list', $data);

Just we have to call the view page by using $this-.load->view method.

Codeigniter-4

echo view('cms\admin_list', $data);

In CI-4 , it is more simplified and we have to just pass view file path to view() function.
For view file lying in other folders outside the app folder. You should define namespaces for them and call them like:-

echo view('Admin\Views\admin_template\admin_mainheader', $data);

12) CONFIGURING MODELS

Codeigniter-3

<?php
class Cms_model extends CI_model {
 
 protected $table = 'cms_pages';

        public function __construct()
        {
                $this->load->database();
        }

      public function functionname()
     {

     }
}
?>
Defining models by extending CI_Model class. Then defining $table in the proteted variable, so can us it all the functions coming under the model. In construct method, loading the database. Then defining each and every functions under it. This is how we did in CI-3.

Codeigniter-4

<?php
namespace App\Models;
use CodeIgniter\Model;

class CmsModel extends Model {
 
 protected $table = 'cms_pages';
 protected $primaryKey = 'page_id';
 protected $allowedFields = ['order','level','parent','position','published','default','featured','title','page_title','content','banner','date_update','seo_title','seo_keywords','seo_description','seo_slug'];

      
        public function get_records() {
 
    }

?>
Here in model, first you have to include namespace path. Then include codeigniter model file. Then define the Model extending Model class. Now here these 3 fields are almost mandatory to put. Sometimes codeigniter doesnt allow saving data without these variables defined in the model.

13) BASIC MODEL FUNCTIONS 

Codeigniter-3

-Insert

$this->db->insert($this->table, $data);

-Update

  $this->db->where('page_id', $id);
   $this->db->update($this->table,$data);

-Delete

  $this->db->where('page_id', $id);
  $this->db->delete($this->table);

-Retreive 
           $this->db->where('id',$id);
        $query = $this->db->get($this->table);
        return $query->result_array();

-Get Last Insert ID

$this->db->insert_id();

-Getting DB error Messages

$this->db->getErrorMessage();


Codeigniter-4


-Insert

$this->insert($data);

-Update

$this->update($id, $data);

-Delete

  $this->delete($id);

-Retreive 

$rec = $this->where(array('level' => '1'))->findAll();

-Get Last Insert ID

$this->insertID();

-Getting DB error Messages

$this->error();

If you watch closely you can see all function calling have been simplified a lot.
























Monday, 17 February 2020

International Exchange Rate Integration to PHP Website

When we are developing  Ecommerce website for international customers, sometimes we want to show item prices in their local currencies. So to update all country currency manually is not a feasible task. So we have to look for some automated way to do this thing. I will explain steps need to taken for doing the same.

1) First thing we have to do is to fix a Base Currency for our website. Its better to put USD as abse currency since it is not fluctuating very much. So you dont have to worry about your items prices every time..

2) You should have a currency rate table in your database. Its fields should be Currencycode, Formal name, rate .etc.. If you need help creating.. download below sql file and export it. Suppose the table name is currency.
https://github.com/litto/Currency-Mysql-table

3) Now create a cron php file named update_exchangerate.php in your server.

4) Copy below code into that file and use yoor own functions for database operations

 $rss = new DOMDocument();
 $rss->load('http://www.floatrates.com/daily/usd.xml');
 $feed = array();
 foreach ($rss->getElementsByTagName('item') as $node) {

  $item = array ( 
   'baseCurrency' => $node->getElementsByTagName('baseCurrency')->item(0)->nodeValue,
   'targetCurrency' => $node->getElementsByTagName('targetCurrency')->item(0)->nodeValue,
   'exchangeRate' => $node->getElementsByTagName('exchangeRate')->item(0)->nodeValue,
   );
  array_push($feed, $item);
 }
 $limit = count($feed);
 for($x=0;$x<$limit;$x++) {

  $baseCurrency = $feed[$x]['baseCurrency'];
  $targetCurrency = $feed[$x]['targetCurrency'];
  $exchangeRate = $feed[$x]['exchangeRate'];
  
    $result = mysql_query("SELECT *  FROM  cms_currency  WHERE `name`='$targetCurrency'", $link1);
    $productdet=fetchquery($result);
    if(count($productdet)>0){
    $currency_id=$productdet[0]['id'];
    if($currency_id!='' || $currency_id!=0)
    {

$inputs1 = array('conv' => $exchangeRate);

updatequery($inputs1,"cms_currency","id='$currency_id'",$dblink);

    }

  }

 } 

5) You can set this file to run as cronjob as frequent as you want.. so it will update the current rates .
If you have linux hosting you can go to Cpanel. Go to advanced section. Click on Cron Jobs. Add a cron job by selecting once per day. Select the hour you need to update.

Command update as wget https://www.website.com/cron/update_exchangerates.php