Creating functions in a quick way in codeigniter - php

As you know, in codeigniter a function name in a class becomes url like :
class Example extends CI_Controller {
function sayHello() {
echo "Hello";
}
}
To display the content of function simply you can show it by using:
www.mydomain.com/example/sayhello
My question is, instead of writing all my function names one by one, how can i form these functions using a loop or by fetching function names from database? For example, i have 100 function name in my database. is it possible to do it writing clear and short code or should i write all functions manually? Thanks...

This has nothing to do with creating functions. Your problem is routing. Solve that:
class University extends CI_Controller {
public function _remap( $university_name )
{
}
}
More info: http://codeigniter.com/user_guide/general/controllers.html#remapping

Related

should I make a class for every page in Codeigniter

Mostly this question is not about programming, it's like the how to use question.
and as I said above, should i make a class for every page in codeigniter? Or I can make function's for every page? if both is right, which one is better?
If you want to make sections/pages like.. "/widgets/view/1" or "/widgets/edit/1" or "/widgets/delete/1" your code would be:
class Widgets extends CI_Controller {
public function view($id)
{
//Go get widget by id $id
}
public function edit($id)
{
}
public function delete($id)
{
}
}
Please check CI Routing http://ellislab.com/codeigniter/user_guide/general/routing.html
You can use 1 controller class with 20 functions for each page or you can have 4 controllers with 5 pages etc...
It depends on the complexity and similarity of your pages. If they are really alike, it could be a waste to create lots of classes, but in general I would create a class per page at least.

PHP - Object Oriented Practices and Inheritance

This is the basic class design
class CustomModule {
public __construct() { }
//Run me first automaticly
public function exec($str) { }
}
class Randomizer extends CustomModule {
public __construct() { }
//Call me
public function exec($str) { }
}
As I am designing a plugin/module system for extern developers I need the CustomModule->exec() to run first, I do not want to leave it up to the devs to have to call base->exec($str).
I want CustomModule::exec() called automaticly before Randomizer::exec() is called without having to put code in Randomizer::exec(). Is This Possible perhaps with magic function?
In my opinion, i would use this way:
Instead of calling _construct in exec of Randomizer, you can define a constructor in Randomizer and call parent::_construct
class CustomModule {
//Run me first automaticly
public function exec($str) { }
public __construct($str) {
$this->exec($str);
}
}
class Randomizer extends CustomModule {
//Call me
public function exec($str) {
parent::__construct($str);
}
}
If your object requires some initialization before you can "release* it into the rest of application, then it means that you need a factory for this. This is how you should be solving it, if you require to call some method only once.
If such execution happens each time you call exec() method, then instead you should be using some sort of containment (in a form of decorator or just you standard composition of objects).
Basically, you need to restructure your code.
After a bit more thought I realized this is BAD design. I have to keep the code base simple and scaleable and this would only make a mess in large projects.
As the only program calling the Randomizer::exec() is my inhouse built program I can just call CustomModule::exec() on the previous line and get a boolean response to see if it should continue to the next line.
Sorry to have to end this Q' short

PHP extending a class

I have a question about extending a class in PHP.
The examples I see on the php site just have 1 line of code in the method...is it the same if the method has tons of code??
If this is the base class:
class BaseClass {
public function WithWayTooMuchCode {
// like 100 lines of code here
}
}
Then do I have to copy all the code over if I want to use the same method, but change only 1 or 2 things?
class MyOwnClass extends BaseClass {
public function WithWayTooMuchCode {
// like 100 lines of code here
// do I have to copy all of the other code and then add my code??
}
}
This seems a little not DRY to me...
Yes, unless those 1 or 2 things happen to be at the beginning or the end. You can call the parent function via
parent::WithWayTooMuchCode();
Which you can place anywhere in the child/overridden method.
If it doesn't feel DRY, consider splitting the function into smaller methods.
do I have to copy all the code over if I want to use the same method,
but change only 1 or 2 things?
No, you don't have to copy all of the code, assuming you're adding to the function and not removing pieces of it.
so it follows:
class BaseClass {
public function WithWayTooMuchCode {
// like 100 lines of code here
}
}
class MyOwnClass extends BaseClass {
public function WithWayTooMuchCode {
parent::WithWayTooMuchCode();
//additionally, do something else
}
}
$moc = new MyOwnClass();
$moc->WithWayTooMuchCode();
You can use the parent::WithWayTooMuchCode() wich will execute the parent method and after you can add your code. It will look like this :
class MyOwnClass extends BaseClass {
public function WithWayTooMuchCode {
parent::WithWayTooMuchCode()
// do I have to copy all of the other code and then add my code??
}
}
You can write down a separate function for that things that you want to do separately in parent class and then Call then in you way.
In other words, separate out the things you need to do separately ans create a function for them. And call them separately in child class. The final function in child class will call parent class function as well those separate functions.
You have a few choices. Assuming;
class BaseClass {
public function WithWayTooMuchCode {
// like 100 lines of code here
}
}
You can do
class MyOwnClass extends BaseClass {
public function AnotherFunction() {
// put other code here
}
}
This allows you to do MyOwnClass->AnotherFunction() and MyOwnClass->WithWayTooMuchCode()
or you could do
class MyOwnClass extends BaseClass {
public function WithWayTooMuchCode() {
// put new code here
}
}
which will allow you to run MyOwnClass->WithWayTooMuchCode() and will ONLY run the "new code", not the "100 lines".
Finally you could do
class MyOwnClass extends BaseClass {
public function WithWayTooMuchCode() {
parent::WithWayTooMuchCode();
// Do more processing
}
}
which will allow you to run MyOwnClass->WithWayTooMuchCode() will run the "100 lines of code" AND the new code. You can put the parent before/after/during your new code, so you can tailor it as required
In addition to the other answers I should point out that this problem can be addressed by events. They are a way to determine points in a class where you can add your own functionality from outside. If you have control over the codebase and the time/inclination you might want to consider implementing this functionality. Unfortunately PHP doesn't support them directly in the way that, say, C# does so you'd have to do the work.
If you only have this issue in a single place I doubt you should bother, but if it's becoming a pattern you might want to consider this approach.

PHP OOP problem

I have classes Video and Audio, which extend class Popular
In class, Video & Audio is a function of "public static function parsing ()" are different in themselves
So, as I can from the class of "Popular" address to the class that calls?
That is in a class of "Popular" is a function of "getSong" which has a function call "parsing ()", but here's how to call this function from the class that turns ..
Hopefully clearly explained ..
Kind of like the opposite function of need "parent"
class Video extends Popular {
public static function parsing()
{
return 'Videooooooooooooo';
.....
}
public static fuinction tratata()
{
....
}
}
class Audio extends Popular {
public static function parsing()
{
.............
return 'Audio';
.....
}
public static fuinction tratata()
{
....
}
}
class Popular {
public static function getSong()
{
$class = '???????';//Video or Audio???
$class::parsing();// ???
}
}
Sorry for bad english.. used google traslate
There is no need for this behavior.
Put the parsing function in the Popular class, so that Audio and Video inherit it. Then your getSong just looks like this.
EDIT: self keyword is bound to the class in which the function is defined. So the below is wrong. The correct answer is to use the static keyword instead - IF you are using PHP 5.3.0 or later.
public static function getSong()
{
static::parsing();
}
below is wrong
public static function getSong()
{
self::parsing();
}
But really, getSong is no longer needed. When a base class implementation is called on a child class, self still refers to the child class, so the correct parsing function will be called automatically.
Did I understand your question correctly?
Also to everyone else: if I'm wrong about this behavior, then shame on me and I need to go back to school. I haven't used this behavior in a while so I may be rusty.
#Tesserex probaly has the best answer.
Not sure whether this is what you mean, but to find out the class name of the current object:
You seem to be using these functions in static context. That makes things more difficult. As far as I know, the only way to find out in that case is PHP 5.3's get_called_class().

Class methods and instance methods in codeigniter, how can I use them?

I am very new to codeigniter but understand OOP and MVC as I do a lot of Rails development. One thing I haven't figured out yet is how to write a class level method in codeigniter and access it in a controller. For example, I have
<?php
class User_model extends Model {
function user_model()
{
parent::Model();
}
public static function get_total_users_count(){
$results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");
if($results){
return $results->num_rows();
}
return 0;
}
}
?>
I think what I have done here is established a class level method for my model that I should be able to call with User_model::get_total_users_count() Now in my controller which a previous programmer called "Welcome" I have something like:
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
$this->load->model('bhr_model');
$this->load->model('user_model');
}
function index()
{
$invite = $this->uri->segment(3);
if($invite == 'invitefriends') {
$pagedata['invitefriends'] = $invite;
} else {
$pagedata['invitefriends'] = '';
}
$pagedata['numberofpeople'] = User_model::get_total_users_count();
$this->load->view('default_page', $pagedata);
}
}
The above method call to get_total_users_count does not work because it says because I am using the db method on a class level function in get_total_users_count. In other words $this has no db method when I reference a class.
So now my question is a bit more theoretical. I always thought that instance methods should only be used when a method is acting on a specific instance of an class. Makes sense, right? However, get_total_users_count is acting on all "users" and counting them. It just seems like that should be a class level method. Do you agree? If do, do you know how I can access the database from withing the framework inside a class level function?
Thanks!
Since you are not instantiating User_model, you must get the CI instance, then use that for your db queries.
Inside get_total_users_count():
$ci_ins =& get_instance();
$ci_ins->db->query();
You can make your class as a helper so it will not be load as a instance. Only the code will be included so you can just call it as:
$sample = class_name::method();
CodeIgnighter works is by instantiating your models as you load them. What Thorpe Obazee said is the correct codeIgnighter way to use your Model.
What you are asking is if you can use a static method as you'd expect in most circumstances, which just isn't how CI works.
To accomplish what you're after, mives points out get_instance() which is the correct way to get at the main CI object. I use that way myself to do what you're doing.
get_total_user_count is more of a function for a user table gateway.
User model should have things like getUsername and getLastLogin.
User Table Gateway should have things like findUserById, createNewUser, and getTotalUserCount
$pagedata['numberofpeople'] = $this->user_model->get_total_users_count();
That's the CI way.

Categories