No need to extend class/library in codeigniter - codeigniter

I would like to check if my assumption about codeigniter is right ?
We would normally extend a class when we are trying to include more functionality to the core, such as MY_Controller extends Controller, MY_Model extends Model etc...
But for example, if we are in the checkout library retrieving some checkout info(eg, product_id), we can just $this->load->library('product_lib',array('product_id'=>$product_id)) and we can easily $this->product_lib->product_name etc... from the checkout library right?
The $this->load thing is kind of equivalent to "hard code" checkout library to extend product_lib(class checkout_lib extends product_lib) to be able to use whatever methods/variables there is in the product_lib.
Please enlighten me.

In CodeIgniter $this->load is like having a resource manager (e.g. resourceManager->load("path/to/file")) and it takes care of loading the library, and passing any arguments you specify and such, easily allowing you to quickly get to using it.
So if you have a variable named product_name in your product_lib then yes calling $this->product_lib->product_name will be accessing that variable.
Really it just places the library into an array with the library name as the key and the instance of the library as the value so calling $this->product_lib is really calling something similar to $loadedLibraries['product_lib'] and returning the instance.
I hope that answers what you are asking, I'm quite tired and could have miss understood you question.

I think you misunderstood the OO paradigm and the way CI work.
$this->load is same with instantiate an object of the library/model, or load the helper file. CI have some sort of management to see if the helper/library/model already uploaded or not.
In other hand, the extends is used when defining a class, to tell PHP that the class will be inherit the parent class properties and method. A class is a blue print of object it will produce.
Maybe you can start by understanding the OO concept first. You can read this as a start, and see the reference used there.

Related

Laravel constants in class Facades

I have a class called Awesome and have used the ServiceProvider and the Facade to register it to the app. Now I can use it as Awesome::Things().
I want to add constants to this class, so I tried
<?php namespace Helper\Awesome;
class Awesome()
{
public static $MOVIE = 'I love the Lego Movie!";
}
but when I call Awesome::$MOVIE, I get Access to undeclared static property: Helper\\Aesome\\Facades\\AwesomeFacade::$MOVIE
Can someone help?
The short version is -- you don't really want to do that. Laravel facades aren't mean to be used like normal classes, and if your application uses them that way you'll likely confuse future developers.
Warning out of the way. When you create a "facade" in Laravel, you're actually creating a class alias. When you added Awesome to the alias list in app/config/app.php, at some point code like the following ran
class_alias('Helper\Aesome\Facades\AwesomeFacade','Awesome');
That means whenever you use a global non-namespaced class Awesome, PHP substitutes Helper\Aesome\Facades\AwesomeFacade. If you wanted to add constants, you'd need to add them to this class.
Laravel's able to pass through methods because of the base Facade class implements a __callStatic method that passes on your call to the actual service implementation object. Facades don't pass on static constant access. Additionally, PHP does not (appear to?) have similar magic methods for passing along requests for constants.
If you're curious about the in depth version of this answer, I'm currently writing a series on Laravel's object system, including some in-depth information about the facade implementation.

Laravel: conflict between model name and built-in facade

I have a Model in my Laravel app called Event. As I just discovered, this creates a conflict between my model and Illuminate\Support\Facades\Event, a built-in facade. The obvious solution here is to either change the name of my Model, which is not ideal because there is really no other name I could give my Model that makes any sense, or to rename the alias in app.php for Illuminate\Support\Facades\Event, which I'd like to avoid for fear of breaking anything that may rely on that alias in the future (I'm afraid I may forget).
It's been suggested that perhaps I could use namespaces, which I attempted as follows:
app/models/Event.php
namespace Models; #<-- I've also tried using "\Models" here
class Event extends \Eloquent{
app/database/seeds/DatabaseSeeder.php
Models\Event::create(); #<-- again, I've also used "\Models\Event"
All 4 combinations above have yielded a Class 'Models\Event' not found error when I run php artisan db:seed.
Perhaps I simply don't understand namespaces properly, but the more pressing issue is how to solve my problem. If it can be solved using namespaces as suggested, great, but I'm open to any other ideas as well.
I made this mistake early on as well, not necessarily understanding the role of namespace throughout the entire app.
The namespace should mark the business logic within the domain or responsibility of the app itself, so giving a namespace of Models isn't necessarily useful. Instead create a root namespace named after the app, your company, you, or whatever you like, then provide a Model sub-namespace.
For example:
namespace MyGreatApp\Models;
class Event extends \Eloquent{ }
Then you would reference this model under:
use MyGreatApp\Models\Event;
$event = new Event();
In the long run this is a cleaner and more organized approach. This does mean moving your models into a different folder, though. But there's nothing wrong with that. At least that way you know you have all your custom code in your MyGreatApp namespace. :)

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Design Pattern for passing a translation object around? For PHP

I'm updating an php web application that is becoming multilingual, based on the Zend MVC framework, and I'm trying to figure out the best approach to passing the translation object to different classes/layers.
Most of my translation is done at the View level, but there are a few cases where I need to return status messages from custom libraries.
I could just create a property for the library and set the translator, but I'm wondering if there is a better way to integrate a translator object into an existing application?
Hold the users lanaguage in a Memento, and pass that through the program logic, when you need to do that translation use it identify the language.
If using Zend_Translate, it's best option to use register.
Zend_Registry::set('Zend_Translate', $translate);
This way all classes can find it automatically (Zend_Form, Zend_Validate, ...)
You could always instantiate the translator in the bootstrap.php so it is available to all classes as a global. That's how I'd do it since you probably need to use it everywhere. It isn't elegant, but it keeps you from having to add code wherever a class needs to throw an exception or return an error message.
If you don't have that many controllers setup can you not extend the base controller and instantiate the translator there? It should be available for use throughout the system then.
Something like this to extend:
<?php
class BaseController extends Zend_Controller_Action
{
public function init()
{
//setup translation object
}
}
?>
You might want to consider to use a dependency injector container, where the translator is an entry that you pass to the objects you need, without manually constructing the object. That way you can easily test and make more high quality (and testable) code
See other question here
How to use dependency injection in Zend Framework?
or this article about plugging ZF 2 DI into ZF1
http://adam.lundrigan.ca/2011/06/using-zenddi-in-zf1/

How do I access the static methods of a custom class in Kohana?

I have a user class with static methods getById and getByUsername
I have the class in the application/libraries folder
How do I call the classes from a controller?
Theory 1:
$this->user = new User();
$this->user::getById;
Theory 2:
$user = new User();
$user::getById;
or is there a clean way of doing it much like how Kohana helpers do it; much like:
text::random();
here's what I am trying to accompplish:
I want to call a static mehthod in the user library from my controller
In PHP you usually include the file (User.php) and the static methods are ready
User:getById
but then how would I do the same thing in an MVC framework?
shall I do an include too?
Like include ('User.php');?
User::getById();
and
User::getByUserName();
Edit: In response to your question edit, generally frameworks have an auto-loading mechanism that will find and load a class file for you once you reference that class. So when you type User::getById(), the PHP interpreter will see that it needs to load the User class (if it hasn't been loaded already), and run the autoloading procedure to find the correct code to include.
I've never used Kohana, but I would be quite surprised if it didn't use some form of autoloading. If it does not, then yes, a simple include('User.php') will be enough to make the static method calls to User work.
The confusing thing is Kohana's convention of writing "helper" classes with lowercase names.
Your user php file will probably all ready be loaded if your using it as a model, so you can use zombat's suggests of User::getById();.
I don't like to follow their naming convensions for helpers or libraries and instead do:
require_once(Kohana::find_file('libraries', 'user_utils', TRUE, 'php'));

Resources