Welcome Guest, Not a member yet? Register   Sign In
Swith to object oriented programming
#1

Hi! I have used CodeIgniter 3 to develop my first web app. I learnt programming (including object oriented programming) years ago but never used in a real application. I have already finished my first working web app but I think I didn't use OOP. I don't make myself clear with how to use it, so I will try to post a short summary of what I have programmed (only what is necessary to understand my approach) and, please, I would like to know how it should look in OOP, if it is worth doing that change to make it easier to add functionality in the future..

MODEL:
PHP Code:
<?php
class Customer_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function getCustomers()
    {
        
$result $this->db->get('customers')->result();
        return 
$result;
    }

    public function getCustomer($id_customer)
    {
        
//database sql
        
        
$customer $query->row();        
        return $customer;
    }

    public function getInvoices($id_customer)
    {
        //database sql
        
        $query $this->db->get();
        return $query->result();
    }



CONTROLLER:
PHP Code:
<?php
class Customers extends CI_Controller {
  
    
public function __construct()
    {
        parent::__construct();
        $this->load->model('customer_model');
    }
    
    
/*
        Show all customers. From this page the detail of one customer can be accessed (calling to the next function)
    */    
    
public function index()
    {
        
$data['customers'] = $this->gestion_model->getCustomers();
        
$this->load->view('customer/all'$data);
    }
  
    
/*
        Show one customer with his/her invoices
    */
    
public function customer($id_customer)
    {
        
$data['customer'] = $this->gestion_model->getCustomer($id_customer);
        
$data['invoices'] = $this->gestion_model->getInvoices($id_customer);
        
$this->load->view('customer/detail'$data);
    }




The customer/all view:
PHP Code:
<?php foreach($customers as $customer): ?>
<tr>
    <td><?php echo $customer->id?></td>
    <td><?php echo $customer->name?></td>
</tr> 



And the customer/detail view:
PHP Code:
<?php echo $customer->id?></td>
<?php echo $customer->name?></td>
<?php foreach($invoices as $invoice): ?>
<tr>
    <td><?php echo $invoice->date?></td> 


The full views and other functions in model and controller (to insert and update data) are not required to undertand how I managed to organize my app.

So, my general question is how to do this app OOP because I understand what I did is not OOP, as I haven't created a "customer" or "invoice" classes. And the particular questions are:
  • Should I define Customer_model as a class representing a customer (with attributes like id, name...), so the class representes ONE customer, or it should represent ALL customers? So, how should I rewrite getCustomers() and getCustomer($id_customer)?
  • Any changes to the controller?
  • Any changes to the views?
Thanks and sorry if this is a very general question, but I really like CodeIgniter and want to fully understand how things should work.
Reply
#2

It is OOP. You are using classes and objects, so it is definitely object oriented programming. By default CodeIgniter 3 returns standard objects (stdObject), but you can also define custom objects. See http://codeigniter.com/userguide3/databa...lt-objects

I never tried it with CI3 but I guess it work. But if you are currently learning CI and are not working on a big existing project, I would advise to learn CI4 instead. You can then use the Entity class for your model objects.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

That is good advice: I am of course more than in time to recode my app to use CodeIgniter 4 and to do it following best programming practices.  I should do both in one go. Could you give me a quick example of how my code should look in CodeIgniter 4 properly using entities?
Reply
#4

I've written an extensive tutorial in 6 part on how to build a basic web app with CI4. Check out part 2 if you just want to learn how to use the Entity class. Obviously, read the user guide too.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#5

(05-06-2021, 02:59 PM)includebeer Wrote: I've written an extensive tutorial in 6 part on how to build a basic web app with CI4. Check out part 2 if you just want to learn how to use the Entity class. Obviously, read the user guide too.

I have well studied your recipes and ingredients full CodeIgniter 4 example. I can see that several files are used to just an easy module to manage one entity with one subentity.

Two questions come to my mind:
  1. The entities are not required, as they provide little functionality at the cost of having two more files to "look at". Right?
  2. The functions provided in MyRecipes, could they be placed either in the Recipes model or in the controller (as private methods)? Why having another file? Just to show recipes we need a view, a  controller and 3 additional files for the library, the model and the entity (not counting the model and entity of Ingredients). Too complicated?
My purpose is not to question if the tutorial is right - it's just that I don't get the reasons that lead to that structure, and understanding that will make me better use CodeIgniter.

Thanks!
Reply
#6

This is a very simple example. The idea behind this tutorial is to show how to use these features. Of course there’s not a lot of logic in these files, but when your application gets more complicated with a lot of new features, you will already have a good structure to expand on. It is a better practice to put a function in its appropriate place instead of trying to put everything in the controller only to save a file or 2. Yes the code in the library could be placed in the controller in private functions. But what will you gain from doing that apart from saving one file? You still have the same amount of code and your controller is harder to read and understand. Also you can’t reuse these functions in a different controller. If you look at part 6 you will see the library is getting a lot of new code that doesn’t belong in a controller. 

For the entities, you are right, they are not absolutely required. But they provide interesting features. For one, it allows the model to return an object of a specific type (Recipe and Ingredient) instead of a generic object. It’s useful to validate you’re working with the right type of object. It also allow you to add logic when setting or getting a value (see the setTitle() function in part 6).

But anyway, CodeIgniter doesn’t force you to use anything. That is what I like about this framework. You have a lot of flexibility. If you wanted to, you could make a web app without using the Entity and Model classes and put everything in the controller. It would work, but it would be a nightmare to maintain in a big application. But if you just want to make quick proof of concept or to test something, it can be done.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#7

Ok, I see now better the point both of using a library and an entity. It just seems very odd to me the appearance of the entity: I had imagined an entity defining what a "recipe" or "ingredient" is, but I don't see all the variables. It's useful that CodeIgniter automatically loads all columns from the database but someone programming the app needs to know the field names in the database. Can the entity be used to define exactly what a "recipe" or "ingredient" is, this is, what attributes (fields in the database) it has one by one, or that's not the purpose of the entity?

And a new question, now that I want to rewrite my app in CodeIgniter 4, what is the best authentication method (a full library with login/logout) for CodeIgniter 4? Or do you recommend writing something from zero?

Thanks!
Reply
#8

Yes you can define all your database fields in the entity if that make it clearer and easier to understand the app data structure. Another cool thing you can do with the Entity class, is you are not required to have exactly the same names as your database. You can map your property names to different database column names.

For the authentication method, I currently use MythAuth from Kilishan (one of CI lead dev) and so far I like it: https://github.com/lonnieezell/myth-auth

In the past, I used Ion Auth from Ben Edmunds for a CI3 web app but I didn’t try the new version for CI4: https://github.com/benedmunds/CodeIgnite...uth/tree/4

Security is serious business. I don’t recommend you write your own from scratch unless you are willing to study the subject and make sure it’s really secure.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#9

Ok, so far so good, I have started a new CodeIgniter 4 project, installed Ion Auth 4 (I had used Ion Auth 3 before so the change is more straightforward to me), created my own "recipes" and "ingredients" entities, models, controller and views and now it's the time to rewrite my app.

As a first question, I have a welcome page showing some indicators, such as the number of recipes. My controller asks for this information to the MyRecipes library. But, in this case, how should I get the total number of recipes? I have written a small method (just one line) on MyRecipes to sql the total number of rows in the recipes table. But this is not using the Recipes model or entity. Am I falling again in the mistake of doing everything in one file, or for this specific purpose there is no way of using the Recipe model to better structure the access? What I have written seems very easy to me but it's true that, if the database changed the name of the recipes table, I would have to manually change it in the MyRecipes method in addition to the Recipes model.

Thank you for your help!
Reply
#10

You don't need to write an SQL statement only to get the number of rows. Just use the model and the query builder. In your controller you can get the number of rows like this:

PHP Code:
$total $myRecipes->recipeModel->countAll() 

It's not always clear what is available from the model class and how to use it. But the model class contain a magic function "__call()" that will check if the function you try to call is available in the query builder, and if it is, it will call it for you. So, you can call the countAll() function directly from your model and it will return the number of row for that table. See: http://codeigniter.com/user_guide/databa...r-database
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply




Theme © iAndrew 2016 - Forum software by © MyBB