Best way to load modules in CodeIgniter MVC - php

I am new to the CodeIgniter fw of PHP and generally have medium experience with MVC. I am working on a project where using modules will make my life a lot easier.
There is something regarding the way you call the modules that is a bit unclear in my head. The solution I had was to call the full module in the controller and pass the code as a variable in the view and then just echo it. Here is a sample of that logic
// Controller
$var['login'] = // code that calls the module
$this->load->view('index', $var);
// View
<div class='navbar'>
<?= $login; ?>
</div>
However after a small search, I found this solution Creating Block/Modules in Code Igniter
(String path of the module (view2) in the controller, pass it to view1 and then call it in the main view): .
Which of the 2 logics is the one that follows the MVC standards in a better way?
UPDATE: I have found the answer on how to do both here: how to load view into another view codeigniter 2.1?
but my question remains the same. Which is the best logic that follows the MVC standards better?

first create model object
like
$model = new mymodel
where u want to call do this
$this->model->your_function_name($parameter);

Related

is this an MVC?

this is a General Question about MVC ..
I wrote a PHP Class that send an Array with Core JsonData Strings to Jquery .. and on Jquery i´m accessing the data and add them to my views ( .append("htm stuff"+jsondata) )
now the Jquery is calling the data from a between.php page that has a catch block with many cases, and upon the called case/function , the between page is calling a function from the php class that sends the json data ..
so i have my oop php model that send the core jsondata , a controller ( catch block), and the view ( the jquery page) .. is this kind of MVC ? or i did miss understand it ?
an example of my code was posted on a previous Question here
Looking at the code you posted in your other post it is not a MVC implementation. Or at least it is a bad implementation.
The MVC is about seperating your presentation from your business logic. Looking at your POST class you don't seperate your business logic from your view:
public static function readPosts(){
$query = new Post_db("SELECT * FROM pmessage
ORDER BY p_id DESC
");
$posts = array();
while($row = $query->fetchRow()){
$posts [] = new Post($row);
}
foreach($posts as $item){
echo $item;
}
}
In this function you get information from your database (business logic) and print content (view). In other words, you combine your MV in one method. So I would say: No, this is not MVC.
In simple word MVC is a pattern, but it should follow some pattern in coding i.e. separation of concern
Model: the property class ,basically container for table data
View:Simple HTML Pages that show data using the models.
Controller:It send commands to the model to update the model's state
.It also work like a router that send model to view and vice-versa.
see the below link for reference...
Help Link
Anything that satisfies or follows Model-View-Controller pattern is called MVC. It's up to us to take it in this way or the other.
In my opinion, like I said if it satisfies MVC needs then call it MVC.

CodeIgniter load controller from view

Is there a way to load a controller from a view ?
Here is what i am affter..
I want to use one view multiple times, but this view is being loaded by separate controller that gives the view, information from the db.So becouse of that information from the model i can't just set $this-load->view(); and etc. Is there a way to do this thing, or it has a better way ?
I think a lot of sites face similar challenges, including one I'm working on that loads the same db content into the sidebar on almost every page in the site. I implemented this with the combination of a library and a helper:
Put the data logic into the library (mine is named common.php). In addition to interfacing with the database, you may want the library to store the data in a local variable in case you want to reference it multiple times on a single load.public function get_total_items()
{
if ($this->_total_items === NULL)
{
$row = $this->ci->db->query("SELECT COUNT(*) FROM items")->row();
$this->_total_items = $row[0];
}
return $this->_total_items;
}
Create a helper to load the library. (Don't load libraries within a view!) I have MY_text_helper that loads the library and returns the data:function total_items()
{
$CI =& get_instance();
return $CI->common->get_total_items();
}
Call the helper function from within the view.<p> Total items: <?php echo total_items(); ?> </p>
Simply put, you can't and shouldn't load a controller from a view. That sad, I understand your frustration because you want to re-use the model-pulling/acting logic in the controller across multiples views.
There are various ways of doing this;
Re-use the models. Your models should be very simple to select data from, and should be sleek, but if you're doing the same thing over and over it does seem stupid. In which case...
Use a controller as a "main container" and extend upon it from any logic you need. So your basically using the controller as a template, which pulls data down from the model, loads the appropriate view.
MVC doesn't work that way ... Just re-use the model - that's why it's separate from the controller. If that doesn't fit your needs, you should probably implement a library that does the logic.
I would use a library.
That way you can wrap up the data retrieval in a reusable package that you can call from any controller you like.
just do this
if you controller named controller1
put a link in view just like that
http://your-site.com/index.php/controller1/
if you want specific function add it to your url
http://your-site.com/index.php/controller1/myfunction
that's it

How do I call other Controllers within a Zend Framework Process and retrieve their rendered view?

I have the following setup:
An endless running PHP process that looks at a job queue which contains module names, controller names, action names and a parameter array.
For every job I want to call the given controllers action and retrieve the rendered view for further processing.
I was thinking about bootstrapping an instance of Zend_Application for every job but not exactly sure on how to handle the rest. Maybe there is also a better way.
So my question is:
How do I call other Controllers within a Zend Framework Process and retrieve their rendered view?
Thanks to everyone in advance!
I would think taking the Front_Controller and dispatching a new request would be the best to do.
Something like this, from your controller (not working code):
$frontController = $this->getFrontController();
$newRequest = new Zend_Controller_Request_Http();
$newRequest->setActionName('newAction');
$newRequest->setControllerName('newController');
$response = new Zend_Controller_Response_Http();
$frontController->dispatch($newRequest, $response);
It might not be this simple, but something to think about...
$this->_forward('otherAction', 'otherControllerOrNull');
http://framework.zend.com/manual/en/zend.controller.dispatcher.html
You can read this thread : Calling member function of other controller in zend framework?
Could you not use an Action View Helper? If you want the output in your controller then you can simply use $this->view->action('someAction', 'someController'); or the ActionStack helper.
In either case, be aware of the performance implications though. See Why the Zend Framework Actionstack is Evil for more details.

What's the best way to transition to MVC coding?

It's been around 5 months since I picked up a PHP book and started coding in PHP. At first, I created all my sites without any organizational plan or MVC. I soon found out that was a pain..
Then I started to read on stackoverflow on how to separate php and html and that's what I have been doing ever since.
Ex:
profile.php <--this file is HTML,css. I just echo the functions here.
profile_functions.php <--this file is mostly PHP. has the functions.
This is how I have been separating all my coding so far and now I feel I should move on and start MVC. But the problem is, I never used classes before and suck with them. And since MVC (such as cakephp and codeigniter) is all classes, that can't be good.
My question: Is there any good books/sites/articles that teaches you how to code in MVC? I am looking for beginner beginner books :)
I just started reading the codeigniter manuel and I think I am going to use that.
EDIT: Is it possible to have a MVC organization structure to your coding without using cake, codeigniter, etc? Basically just separate say profile.php into 3 different files(the view, controller, model)
to answer your question
Is it possible to have a MVC
organization structure to your coding
without using cake, codeigniter, etc?
Basically just separate say
profile.php into 3 different files(the
view, controller, model)
absolutely...
first file profile.php ( the view, what gets hit by the browser )
<?php
include( 'controllers/UsersController.php' );
$controller = new UsersController();
$controller->profile();
$pageData = $controller->data;
?>
the controller
<?php
include 'models/UsersModel.php';
class UsersController{
public $data;
public $model;
public function __construct(){
$this->model = new UserModel();
}
public function profile(){
$this->data = $this->model->findUser();
}
}
the model
<?php
class UsersModel{
public function __constuct(){
// connect to your db or whatever you need to do
}
public function findUser(){
return mysql_query( "SELECT * FROM users WHERE users.id = 2 LIMIT 1" );
}
}
MVC is just a design pattern. It's not really something you can "code in".
If you like to code in PHP, here is an article regarding MVC in PHP. It has an overview explaining the design pattern, and then an example follows.
How I learned was by going through this tutorial:
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/
The primary focus is to learn the Symfony Framework, but by default, you will be exposed to and learn good MVC principles.
It's not PHP, but see if you can get a copy of Tate's Bitter Java. It will discuss the organizational side of things (how and why the organizational code improves stuff).
I'm a bit hesitant to recommend one of the great Java books for PHP programming, but this book is one of the few that starts with code written without an organizational plan and improves it into a MVC like structure without the use of 3rd party libraries. This way it teaches you what the organization is about from a practical point of view. Hopefully once you understand the pattern, it won't be too difficult to translate the ideas into PHP.
Another alternative is to grab one of the dozens of PHP frameworks and recode to the framework. Doing so will get your results much faster, but the drawback is that you'll likely understand those results in greater detail, and there is a small chance your code will not behave the same after you rewrite it from scratch. We all like to think the new stuff will do everything the old stuff did, but often we forget something (or it behaves differently).
MVC is a "generic" design pattern that is not particular to any language. More of a coding philosophy. On the most basic level it's just separating data from business logic from presentation. Below is a simple example of a "templating" system using MVC. You would be able to swap out any of the parts without breaking anything, and the data is not tied to the formatting/display. This is sample code, not efficient.
Model, get the data:
function getName($id) {
$name = array('_first_'=>'Joe', '_last_'=>'Smith', '_mi_'=>'C');
return $name
}
Controller, processes it:
$name = getName(1);
$name['_fullname_'] = $name['_first_'].' '.$name['_mi_'].'. '.$name['_last_'];
outputView($name);
View, output the content:
// Example html file: <b>Hello _fullname_, how are you</b>
function outputView($view, $data) {
switch ($view) {
case 'xml':
$out = file_get_contents('view.xml');
case 'html':
$out = file_get_contents('view.html');
case 'json':
$out = file_get_contents('view.json');
}
$search_for = array_keys($data);
$replace_with = $data;
echo str_replace($search_for, $replace_with, $out);
}

CakePHP View including other views

I have a CakePHP application that in some moment will show a view with product media (pictures or videos) I want to know if, there is someway to include another view that threats the video or threats the pictures, depending on a flag. I want to use those "small views" to several other purposes, so It should be "like" a cake component, for reutilization.
What you guys suggest to use to be in Cake conventions (and not using a raw include('') command)
In the interest of having the information here in case someone stumbles upon this, it is important to note that the solution varies depending on the CakePHP version.
For CakePHP 1.1
$this->renderElement('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.thtml, where $flag will have the value of whatever you pass to it.
For CakePHP 1.2
$this->element('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.ctp, where $flag will have the value of whatever you pass to it.
In both versions the element will have access to all the data the view has access to + any values you pass to it. Furthermore, as someone pointed out, requestAction() is also an option, but it can take a heavy toll in performance if done without using cache, since it has to go through all the steps a normal action would.
In your controller (in this example the posts controller).
function something() {
return $this->Post->find('all');
}
In your elements directory (app/views/element) create a file called posts.ctp.
In posts.ctp:
$posts = $this->requestAction('posts/something');
foreach($posts as $post):
echo $post['Post']['title'];
endforeach;
Then in your view:
<?php echo $this->element('posts'); ?>
This is mostly taken from the CakePHP book here:
Creating Reusable Elements with requestAction
I do believe that using requestAction is quite expensive, so you will want to look into caching.
Simply use:
<?php include('/<other_view>.ctp'); ?>
in the .ctp your action ends up in.
For example, build an archived function
function archived() {
// do some stuff
// you can even hook the index() function
$myscope = array("archived = 1");
$this->index($myscope);
// coming back, so the archived view will be launched
$this->set("is_archived", true); // e.g. use this in your index.ctp for customization
}
Possibly adjust your index action:
function index($scope = array()) {
// ...
$this->set(items, $this->paginate($scope));
}
Your archive.ctp will be:
<?php include('/index.ctp'); ?>
Ideal reuse of code of controller actions and views.
For CakePHP 2.x
New for Cake 2.x is the abilty to extend a given view. So while elements are great for having little bits of reusable code, extending a view allows you to reuse whole views.
See the manual for more/better information
http://book.cakephp.org/2.0/en/views.html#extending-views
Elements work if you want them to have access to the same data that the calling view has access to.
If you want your embedded view to have access to its own set of data, you might want to use something like requestAction(). This allows you to embed a full-fledged view that would otherwise be stand-alone.
I want to use those "small views" to
several other purposes, so It should
be "like" a cake component, for
reutilization.
This is done with "Helpers", as described here. But I'm not sure that's really what you want. The "Elements" suggestion seems correct too. It heavily depends of what you're trying to accomplish. My two cents...
In CakePHP 3.x you can simple use:
$this->render('view')
This will render the view from the same directory as parent view.

Categories