• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write a good library

#1
Hello,

I work with CodeIgniter since 1 year and after little projects,  I want to work on a big project. Of course I choose CodeIgniter for this project because I think it's a very good and powerful framework.

I want to write a good code and use many libraries. 
But I don't know if I wrote a good and reusable code.

For example I manage customers in my application and I wrote a library to add, update, delete my customers.
Here is an excerpt of my code :

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Customer {

    public 
$CI;
    public 
$rules;
    public 
$customer;


    public function 
__construct($params)
    {
        $this->CI =& get_instance();
        
        $this
->CI->config->load'customerConfig' TRUE );
        $this->CI->config->load'customerValidationRules' TRUE );
        $this->CI->load->model('customerModel');
        $this->rules config_item('customerRules');
        $this->customer config_item('customer');
    }


    public function 
add()
    {
        $this->CI->load->helper(array('form'));
        $this->CI->load->library('form_validation');
        $this->CI->form_validation->set_rules($this->rules['add_rules']);
        
        
if( $this->CI->form_validation->run() !== FALSE )
        {
            foreach( $this->customer['customer_fields'] AS $key => $element )
            {
            if( !$this->CI->input->post($element) )
            {
                $datas[$key] = NULL;
            }
                
            $datas
[$key] = $this->CI->input->post($element);
            }
            
            $address_id 
$this->add_address$this->customer['address_field'] );    
            $date date('Y-m-d H:i:s');
            
            $datas
['address'] = $address_id;
            $datas['password'] = password_hash$this->CI->input->post('password'), PASSWORD_BCRYPT);  
        }
            
        $datas
['status'] = 1;
            
        $datas
['date_create'] = $date;
        $datas['date_update'] = $date;
            
        
if( $this->CI->customer_model->add($datas) )
        {
            $this->CI->session->set_flashdata('success''Congratulations your customer has been registered');
            return TRUE;
        }    
            
        $this
->CI->session->set_flashdata('error''An error has occured, please try again later');
        return FALSE;
    }


I have a config file with customer fields and a form validation file.
I have a customer model that looks like this :

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Customer_model extends CI_Model {
    
    public function 
__construct()
    {
        $this->load->database();
    }


    public function 
add($data)
    {
        return $this->db->insert('customer'$data);
    }


With my library, is my approach good ?
Thank

Sorry if my english is not good, I'm french.
Reply

#2
I'm not going to provide a comprehensive analysis of your code, but from my glance at it, it looks like your Customer library should just be code in your customer model.
Reply

#3
Ok you think I can put my library code in my model.

It's true that my controller calls my library to call my model while I could call my model directly from my controller.
But do you think that it's reusable for another project ?

I search to make a reusable code that I can copy/cut my files in another project and it works.

I tend to repeat a lot of code in my controllers and would like to develop more cleanly.

Thank you for you're answer
Reply

#4
I have to also agree @skunkbad that most of your code should be in your model because it is business logic.
What did you Try? What did you Get? What did you Expect?

Joined the CodeIgniter Community in 2009.          ( Skype: insitfx )
Reply

#5
In my opinion, there is one of the best libraries helper for making the models easier which called MY_Model, here is the link:

https://github.com/jamierumbelow/codeigniter-base-model

I am using it in all my projects and it seem to help me allot.
Reply

#6
I think your approach is good. But your example is poor. Add, update and delete can be called directly from your model, but I like the rule of only libraries calling models (this is my personal thing of course, not a rule as such).

So if you have a customers library, and you are adding a customer, your controller should call the library function 'add_customer'. That library function is where I would put the business logic. So it adds the customer by calling the customer_model and the customer_model writes the record.

But it might be that you first need to check the customer does not already exist. So your library will call the customer_model to see if the customer already exists. If not, then it creates a new customer.

It might be that when you add a customer you want to alert the sales team to a new customer, so after writing a new customer the library calls the sales_team_model to add a new lead. (Or whatever).

Perhaps the new customer needs to be credit checked, so a credit_check alert is written to another table, so accounts can be alerted.

Maybe the customer needs to be in a certain area, like in the UK, so the library would process the address fields before adding the customer.

It might be that you need to check the customer against a blacklist of banned users, the list of logic that might be needed for adding a customer is theoretically endless. Perhaps the age of the customer has to be over 18 etc. All this logic would be in your customer library, where any controller can add a new customer just by calling it. And if the business logic changes, only the library needs to be amended. Not the models (presuming the database has not changed) and not the controllers.

The library containing the business logic does all the work surrounding the operation of adding a new customer, the models just do the database interactions, the simple steps to get or write data. The library is where the thinking and calculations on that data is done.

- Controller, gets the request calls relevant library functions, and requests a view.
- Library, gets the controller request, does all the hard work for that request, calls whatever model functions it needs during that process, and returns error messages, success messages or data as required back to the controller.
- Models interrogate the database, and return the results to the library.
- Views called by the controller present the information from the libraries in a page.

If you have no business logic, then call the model directly from your controller. If the library has no work to do but act as a middle man then why bother with it.

So yes, I think your approach is good presuming you are going to be doing more complex stuff in your libraries, rather than just passing data straight through to your models and back to your controller.

Personally, I like very thin controllers, fat libraries, and thin models. But CI lets you do it whatever way suits you best, and I love that.

Paul.
Reply

#7
@ehabafia
Thank you I look your link.

@PaulD
Thank you for this big answer.
I think like you to keep very thin controllers and do many things in my library.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.