I have a table of data from a database that I want to display on various pages of my website. Ideally, i would like to just have an include or something that will go off and get the data, and return the html table. The html and data will be identical everytime I need to use this.
I wanted to know the best way of doing this
Thanks
EDIT
If this helps, something similar to a Django "inclusion" custom tag...for any django developers reading
you need to pass the variable $data to the view method.
This is your code:
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view');
}
Please change it to this in order to load the $data into the view:
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view',$data);
}
You should use a function in a model to fetch the data you need. Your controller calls the model function and sends the returned information to a view. You don't need to use traditional php includes with Codeigniter. I recommend a review of the user guide. It's very good and will tell you all the basic stuff you need to know to develop with CI. But to get you started, you watn to use Models, Views, and Controllers. Your url will tell CI what controller and function inside that controller to run. If your url is
http://www.example.com/my_controller/load_my_view
Then CI will do what is inside the load_my_view function in the my_controller controller. function load_my_view in turn instantiates a model "my_table" and runs a database query, returns information that the controller sends to the view. A basic example follows:
Your model
class my_table extends CI_Model{
function my_data(){
$this->db->select('column_1,column_2,column_3');
$this->db->from('my_table');
$query = $this->db->get();
if($query->num_rows()>0){
$result = $query->result();
}
else{
$result = false;
}
return $result;
}
}
Your controller
class my_controller extends CI_Controller{
function load_my_view(){
$this->load->model('my_table');
$data['my_results'] = $this->my_table->my_data();
$this->load->view('my_view');
}
}
Your View
<ul id = "my_db_results">
<?php foreach($my_results as $result):?>
<li><?php echo $result->column_1." : ".$result->column_2." ( ".$result->column_3." )";?></li>
<?php endforeach;?>
</ul>
It looks like a good oportunity to use cache: http://codeigniter.com/user_guide/libraries/caching.html
Ok, so here is one thing that worked for me, but its definitely not perfect.
I created a view in which made a call to the model getting the data then put the data into a table. This way, I only have to include this view to put the table anywhere.
I understand this completely ruins the point of having a MVC framework, but hopefully it demonstrates what I want to do...and it works
Related
Okay, so i have pages controller and user_authenticator controller.
pages controller is like a terminal to my views whilst the user_authenticator controller does the functions that relates to users like registration/logging in.
Whenever i'm done with a function in user_authenticator say for example logging in, how do i load the views via pages controller?
Login->user_auth(controller)->acc_model(model)->user_auth(controller)->view.
to
Login->user_auth->acc_model->pages(controller)->view.
It would be a boon for me if you guys can tell me if what i'm doing is impractical and a better way to do things. Or maybe i should just stick to loading views on the controller i used previously.
EDIT: so i may have forgotten the purpose of my pages controller but i remembered due to a moment of clarity from my foggy and tired mind.
I made a pages controller solely to load views, i guess in a sense, pages won't be loading ALL view but atleast most of the views, for example, if i had links in my views to other views, i would link them via the pages.
For specific functions that need specific controllers i guess i can let them handle loading some views.
Then again, if someone could tell me what i'm doing is a waste of time and should just delete pages controller please tell me so, i'd like to know why.
also if you have any suggestions for further uses of my pages controller thatd be great!
Also regarding session. I have a base controller.
<?php
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function is_logged_in($data){
$session = $this->session->userdata();
if($session['isloggedin']['username'] == ''){
return isset($session);
}else{
return FALSE;}
}
}
?>
How do i make it so that it automatically runs and checks for every controller i load if there are any session set?
Do i have to put it into a constructor? or do i have to call the base controller method from all controllers?
Here is the best solution for you.
You can use Hooks
Step1:
application/config/config.php
$config['enable_hooks'] = TRUE;//enable hook
Step2:
application/config/hooks.php
$is_logged_in= array();
$is_logged_in['class'] = '';
$is_logged_in['function'] = 'is_logged_in';//which function will be executed
$is_logged_in['filename'] = 'is_logged_in.php';//hook file name
$is_logged_in['filepath'] = 'hooks';//path.. default
$is_logged_in['params'] = array();
$hook['post_controller_constructor'][] = $is_logged_in;//here we decare a hook .
//the hook will be executed after CI_Controller construct.
//(also u can execute it at other time , see the CI document)
Step3:
application/hooks/is_logged_in.php //what u decared
<?php
//this function will be called after CI controller construct!
function is_logged_in(){
$ci =& get_instance();//here we get the CI super object
$session = $ci->session->userdata();//get session
if($session['isloggedin']){ //if is logged in = true
$ci->username = 'mike';//do what you want just like in controller.
//but use $ci instead of $this**
}else{
//if not loggedin .do anything you want
redirect('login');//go to login page.
}
}
Step4:application/controller/pages.php
<?php
class pages extends CI_Controller{
function construct ........
function index(){
echo $this->username;//it will output 'Mike', what u declared in hook
}
}
Hope it will help u.
I want to know is there any way to access table data without passing it from controller to view in laravel 5 ?
I have an Options table in my database that stores all my project options. it has three column:
id
name
value
Now I want to access each option value in my master.blade.php file.
what is the best way to do it.
If you understand what MVC is all about then you should know that passing a variable from controller to your view is the best practice. View is simply used for presentation and should only be used for presentation purpose for the sake of separation of concern.
With that been said the best approach is:
Create a model for options then pass it through your controller to the view.
For example:
use App\Option;
PageController extends Controller{
public function __construct(Option $option){
$this->option = $option;
}
public function about(){
$options = $this->option->list('id','value');
return view('about', $options);
}
}
To make variable global in all view see my answer here:
Laravel 5 - global Blade view variable available in all templates
Well there can be multiple ways available, but passing your Table data directly into views is not a recommended way, It would be much better if you follow the proper way, means from Controller to Model. Well its upto you. here is my suggested possible ways.
Method 1 (about which you are asking)
in your master.blade.php file, you can also do this,
<?php
$v = new \App\Message(); // your model object
echo $v ->testmeee(); // its method
?>
Method 2
If you are trying to use your Table data globally(means you want options data should be available on all pages/views), then this one is highly suggested way.
Goto your App/Http/Providers/AppServiceProvider.php file
view()->composer('*', function ($view)
{
$user = new \App\User();
$view->with('friend_new_req_count', count($user->getLoggedinUserNewFriends()));
});
now this variablefriend_new_req_count with data would be available in all views (only in views) means you can access in view {{$friend_new_req_count}}
I am using a function to write a query, and I am trying to return the variable the function returns and use it in a view. In my model:
Fan.php
public function sample_query() {
$count = User::where('fbid', '=', 421930)->count();
return $count;
}
In the view I am simply trying to call it with:
#sample_query();
This is not working. I am new to this type of thing, and I suppose I don't know how to access the data pulled by queries in the model in the view. Please let me know if there is a better way, or why this isn't working. Thank you!
For your question it seems View Composer will solve your problem
View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".
View::composer('profile', function($view)
{
$view->with('count', User::count());
});
for more info read this
starting from the supposition that you have a User class:
{{ User::sample_query() }}
I want my urls to look like:
www.domain.com/catalog/category_name/category_id/product_name/product_id.
How should my controllers look like to accomplish this?
It's ok for the Controller to have Catalog and Function category_name in it.
But what will be my product controller and function. How can I make a structure like this.
Do I need to have a specific file structure?
I use CodeIgniter framework. Thanks for your help.
In general the controller must not be changed (if it accepts the product id as parameter).
All other information can then be put in the url from the database (querying via the product id and getting related information) through URI Routing changes.
your controller method should be like this
<?
//..
public function category_name($category_id,$product_name,$product_id){
// some cool code
}
//..
?>
As you question is very vague - so is my answer - but this function achieves what you asked
Class Catalog extends CI_Controller
{
public function category_name ($category_id, $product_name, $product_id)
{
// your function
}
}
I'm fairly new to Zend Framework and MVC in general so I'm looking for some advice. We have a base controller class in which we have some methods to obtain some user information, account configurations, etc.
So I'm using some of those methods to write out code in various controllers actions, but now I want to avoid duplicating this code and further more I would like to take this code outside of the controller and in a view helper as it is mainly to output some JavaScript. So the code in the controller would look like this:
$obj= new SomeModel ( $this->_getModelConfig () );
$states = $obj->fetchByUser ( $this->user->getId() );
//Fair amount of logic here using this result to prepare some javascript that should be sent to the view...
The $this->_getModelConfig and $this->user->getId() are things that I could do in the controller, now my question is what is the best way to pass that information to the view helper once i move this code out of the controller ?
Should I just call these methods in the controller and store the results into the view and have the helper pick it up from there ?
Another option I was thinking of was to add some parameters to the helper and if the parameters are passed then I store them in properties of the helper and return, and when called without passing the parameters it performs the work. So it would look like this:
From controller:
$this->view->myHelper($this->user->getId(), $this->_getModelConfig());
From view:
<?= $this->myHelper(); %>
Helper:
class Zend_View_Helper_MyHelper extends Zend_View_Helper_Abstract
{
public $userId = '';
public $config = null;
public function myHelper ($userId = null, $config = null)
{
if ($userId) {
$this->userId = $userId;
$this->config = $config;
} else {
//do the work
$obj = new SomeModel($this->config);
$states = $obj->fetchByUser($this->userId);
//do the work here
}
return $this;
}
}
Any advice is welcomed!
Firstly the ASP style ending tag here at "$this->myHelper(); %>" is bad practice, with that said it is more advisable to keep the logic in the model and the controller just being used to call the model, get the results and spit that to the view for viewing.
what I would do is, if i simply want to pass a bunch of values to the view, i stuff them in an associative array and send them over.
anyway you should not be doing your ...
"//Fair amount of logic here using this result to prepare some javascript that should be sent to the view..."
part in the controller, I would advice you to make a new model that does that logic stuff for you, and you just call your model in the controller pass it what ever arguments that are needed and then spit the result of that to the view.
The best way is to get the data from your model throught your controller, and then pass to the view. But if you really need a custom helper to echo the view parts, we only will know if you say exactly what you're trying to do.
If you already have this logic in a helper, try to just pass the parameters in your view myhelper($this->params); ?>
You may want take a look at this approach too:
// In your view to put javascript in the header
// You can loop trought your data and then use it to generate the javascript.
<?php $this->headScript()->captureStart(); ?>
$().ready(function(){
$('#slideshow').cycle({
fx: 'fade',
speed: 1000,
timeout: 6500,
pager: '#nav'
});
});
<?php $this->headScript()->captureEnd() ?>