In one of my controllers to fetch all the data for my general view page I use a foreach loop and then $object->column_name but now I have decided I would like to do a couple of things with this data:
Edit it -> It is an edit page for each $object by its $id
Use the $object->name field via the controller to enable me to use it in a $data['pageTitle']= Edit '.$object->name.';
What would be the best way to change the model below so that I can use it for many purposes / different ways of displaying the data for manipulation?
public function showAll()
{
$database = $this->db->get('form');
if($database->num_rows() > 0)
{
$row = $database->result();
}
return $row;
}
It is good practice to keep the database query part in your model rather than the controller.
In your controller you can do something like:
$recs = $this->sample_model->model_function();
foreach ($recs as $r)
{
$r->additional_info_appended_to_each_row = 'whatever';
}
This way you can append an additional variable to each database row for displaying / editing etc.
That code doesn't really show us enough of the relevant code to be able to answer that question. Assuming $database->result() returns an array of rows (a database query's result set) then the data it contains depends on how the query looks. All you show is is $this->db->get('form'), which can mean just about anything.
A generic answer to your question would be: Alter the SQL query to include the id and name fields. Then inject those into your view through your controller. (Or get them directly through the view. That's up to you.)
Not knowing a thing about your controllers or your views, here is an example that assumes your views extend the Smarty template engine.
public function GeneralController
{
public function defaultAction()
{
$model = new GeneralModel();
$objects = $model->getAll();
$view = new GeneralView();
$view->assign("objects", $objects);
$view->show();
}
}
The Smarty template would then use those rows when generating the HTML
{foreach $objects as $object}
<section class="object">
<header>
<h1>{$object->name}</h1>
</header>
<p>{$object->contents}</p>
<footer>
Edit
</footer>
</section>
{/foreach}
Related
I'm currently learning the ropes of the MVC pattern and came across a problem I can't seem
to fix in a way I want and is in line with the MVC pattern.
I have set up the router, controllers and views up successfully.
The only thing I don't really get is the use of the Model. I know it's supposed to
serve the Data to the view, and here it is I have a problem.
I want to pass a function thru my view method, but it executes before it should be.
is there a way
I will try to be as specific as possible about the situation so sorry for the long post.
The controller class is this:
class Controller{
private $tpl_name = 'default';
public function model($model){
require('../admin/model/'.$model.'.model.php');
return new $model();
}
public function view($page_title,$file_paths,$params,$data = []) {
// takes an array with the file paths
$this->content = $file_paths;
$tpl_name = $this->tpl_name;
require_once('templates/'.$tpl_name.'/header.php');
require_once('templates/'.$tpl_name.'/nav.php');
require_once('templates/'.$tpl_name.'/content-top.php');
foreach ($file_paths as $content){
require_once('view/'.$content);
}
require_once('templates/'.$tpl_name.'/content-bottom.php');
require_once('templates/'.$tpl_name.'/footer.php');
}
}
The view renders the template I want, takes parameters from the router and, the data that
needs to be handled in the desired view. So far so good.
I want to serve my posts in my admin panel that displays a table of all the posts in the DB.
I have written a method that fetches the data, and a method that writes the data.
class Post{
......
//other functions above
public function displayPosts(){
// get's all the posts form the data base, returns an object array
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
}
static public function write(Array $posts){
foreach($posts as $single){
// for each object in the array, assign the vars so the view can handle them
// to create a single row in the table for each object:
$trashed = $single->getTrashed();
$id = $single->getID();
$title = $single->getTitle();
$category = $single->getCategory();
$content = $single->getContent();
$author = $single->getAuthor();
$date = $single->getDate();
$approved = $single->getApproved();
$dbt = $single->getDbt();
// This is a template which represents a table row with the post data I need.
require('view/content_table.php');
}
//controller file (needs to moved to other file later): handles approve/remove/edit/delete actions.
require('view/manage_content.php');
}
}
Now we have arrived at the problem:
When I call the model in my controller and render the view, it will execute immediatly
before the rest of my view loads, resulting in errors, although it displays the data,
it is not in my template, but above it, just in plain text.
errors:
Notice: Undefined variable: _SESSION in /Volumes/HDD Mac/Websites/server/admin/view/content_table.php on line 8
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at ...)
class Dashboard extends Controller {
public function index($params = null){
$model = $this->model('Post');
$posts = $model->displayPosts();
// view takes: page_title,[array of view files],params from the router,array of data from model
$this->view('Dashboard',['admin.php'],$params,[ 'posts' => $posts]);
}
}
Before I was trying to use MVC I just outputted this in my view:
And it worked just fine.
Non relevant HTML above
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
Non relevant HTML below
But now when I pass the display post function, I just want to do this in my view:
echo $data['posts'];
which doesn't work because it already executed my Write function.
The only way I could work around like this was by adding the content of my write function to the view,
and only pass the fetchContent method to my view method (this will output an array of objects).
But since I need this info in two place I dont want to repeat this code, I would prefer echoing
all out.
Non relevant HTML above
$posts = $data['posts'];
foreach($posts as $single){
// for each object in the array, assign the vars so the view can handle them
// to create a single row in the table for each object:
$trashed = $single->getTrashed();
$id = $single->getID();
$title = $single->getTitle();
$category = $single->getCategory();
$content = $single->getContent();
$author = $single->getAuthor();
$date = $single->getDate();
$approved = $single->getApproved();
$dbt = $single->getDbt();
// This is a template which represents a table row with the post data I need.
require('view/content_table.php');
}
//controller file (needs to moved to other file later): handles approve/remove/edit/delete actions.
require('view/manage_content.php');
Non relevant HTML below
Is it bad practise to just skip the use of the Model here and do it like this:
Non relevant HTML above
$posts = Post::fetchContent('posts',0);
// array get's passes to the write function which will write out the data.
$writer = Post::write($posts);
Non relevant HTML below
Or is there a way to rewrite my Post::Write function? Or just use the foreach loop in the view?
Thank you all for taking the time!
If you need more info, just ask:-)
I've been using 2 methods to render data.
The first one:
function name($id,$name){
return '<div id="'.$id.'">'.$name.'</div>';
}
echo implode($pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_FUNC,'name'));
The second one:
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
foreach($users as $user){
echo name($user->id,$user->name);
}
I don't really understand how PDO::FETCH_FUNC works. I already tried to figure it out. However, this is not so well-documented.
Could anybody please explain this fetch mode? And also, which one performs better? Thank you.
Both methods are wrong and you have to learn how to use templates and how to separate business logic from presentation logic.
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
tpl::assign('users', $users);
is ALL the code for the business logic part.
then in template
<?php foreach $users as $row): ?>
<div id="<?=$row->id?>"><?=$row->name?></div>
<?php endforeach ?>
Frankly, your business logic should contain not a trace of HTML while presentation logic should contain not a single database call.
Here is an example:
$stmt = $pdo->query('SELECT id, name FROM user');
$data = $stmt->fetchAll(PDO::FETCH_FUNC, array('Foo', 'name'));
Class Foo {
public static function name($id, $name) {
return '<div id="'.$id.'">'.$name.'</div>';
}
}
So basically FETCH_FUNC mode fetches records to user defined function. This is useful because you can manipulate the result.
Use static method if you are not passing in an object of the class. You can just pass in an object and not use static method just the way #Barmar noted in comments.
i need differents results from a model but i don't understand if it is correct make a single call and leave to model all the work or make more calls and collect the result to pass to the view when tables aren't joined or when i need fetch one row from a table and differents rows from others.
First example (more calls, collect and send to view):
CONTROLLER
// call functions of model
$modelName = new Application_Model_DbTable_ModelName();
$rs1 = $modelName->getTest($var);
$rs2 = $modelName->getTest2($var2);
// collect data
$pippo = $rs1->pippo;
if ($rs2->pluto == 'test') {
$pluto = 'ok';
} else {
$pluto = 'ko';
}
// send to view
$this->view->pippo = $pippo;
$this->view->pluto = $pluto;
MODEL
public function getTest($var) {
...
select from db...
return $result;
...
}
public function getTest2($var) {
...
select from db...
return $result;
...
}
Second example (one call, model collect all data, return to controller and send to view):
CONTROLLER
// call one function of model
$modelName = new Application_Model_DbTable_ModelName();
$rs = $modelName->getTest($var);
MODEL
public function getTest($var) {
...
select from db...
if ($result > 0) {
call other function
call other function
collect data
return $result;
...
}
Thanks
There's no one correct answer to this question, but in general, you should endeavor to keep your business logic in one place. Think of it as, "thin controller, thick model." I.e., keep the controllers as small and simple as possible and put all the business logic in the models.
There seems to be a few questions here:
But if i don't need to interact with db and i need only a simply
function is better put that function in model? For example:
CONTROLLER:
public function printAction() {
$data = $this->getRequest()->getPost();
$label = "blablabla";
$this->view->label = $label;
}
first, in the context of Zend Framework this particular example doesn't make much sense. The whole point of the controller is to populate the view template. However, I do get the idea. I would point you to Action Helpers and View helpers as a means to address your concerns. You can always add a utility class to your library for those pieces of code that don't seem to fit anywhere else.
Action Helpers typically are employed to encapsulate controller code that may be repetitive or reusable. They can be as simple or as complex as required, here is a simple example:
class Controller_Action_Helper_Login extends Zend_Controller_Action_Helper_Abstract
{
/**
* #return \Application_Form_Login
*/
public function direct()
{
$form = new Application_Form_Login();
$form->setAction('/index/login');
return $form;
}
}
//add the helper path to the stack in the application.ini
resources.frontController.actionhelperpaths.Controller_Action_Helper = APPLICATION_PATH "/../library/Controller/Action/Helper"
//the helper is called in the controller
$this->_helper->login();
a View helper does the same thing for the view templates:
class Zend_View_Helper_PadId extends Zend_View_Helper_Abstract
{
/**
* add leading zeros to value
* #param type $id
* #return string
*/
public function padId($id)
{
return str_pad($id, 5, 0, STR_PAD_LEFT);
}
}
//in this example the helper path is added to the stack from the boostrap.php
protected function _initView()
{
//Initialize view
$view = new Zend_View();
//add custom view helper path
$view->addHelperPath('/../library/View/Helper');
//truncated for brevity
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer');
$viewRenderer->setView($view);
//Return it, so that it can be stored by the bootstrap
return $view;
}
//and to use the helper in the view template
//any.phtml
<?php echo $this->padId($this->id) ?>
i need differents results from a model but i don't understand if it is
correct make a single call and leave to model all the work or make
more calls and collect the result to pass to the view when tables
aren't joined or when i need fetch one row from a table and differents
rows from others.
This question is more about structure then about correctness.
You can interact with your database table models in Action and View helpers for simple/repetitive queries if you need to, however most developers might frown on this approach as being difficult to maintain or just ugly.
Many people seem to favor Doctrine or Propel to help them manage their database needs.
At this point I like to roll my own and currently favor domain models and data mappers, not an end all be all pattern, but seems to be appropriate to your question.
This is not a simple suggestion to implement for the first time, however i found two articles helpful to get started:
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
and if you really want to get into it try:
http://survivethedeepend.com/
I hope this answers at least a part of your questions.
I consider myself as a php beginner, so it may be possible that this question is too easy for someone, but I got really confused on how to solve it. I am trying to loop something from the database in my views. So, in a quick way I solved it like this:
I've created a function in my model that does the loop and in the same time is creating the html and saves it in a variable. Then, I get that variable from my controller and I pass it in my view. But, it seems that this is not a good way to solve it, since if I want to change my html I need to enter my model function instead some of the view files.
Then, I've created another function in my model that looks like this:
function displayUsers() {
$sql = $this->pdo->prepare('select * from user');
$sql->execute();
while($row = $sql->fetch())
$results[] = $row;
return $results;
}
Now... I take the result in my controller, and send it in the view, but then... I don't know how to extract the results from my variable. I have done something like this:
while($output) {
foreach($output[$i] as $key => $value)
$data[$key] = $value;
echo $data['email'];
$i++;
}
But then, in the end it says to me undefined offset, which means I am referring to an array key that doesn't exist. Can anyone help me on how to solve this issue?
Proper MVC shouldn't have any output in the model or the controller.
Ideally you would have a model that just gets the raw data and returns it in the controller. The controller can then build up an array of values that we'll call data. For example:
Controller
$data['users'] = $this->MyModel->getusers(); // Getting the users from your model
$data['posts'] = $this->MyModel->getposts(); // Getting the posts from your model
$this->getTemplate('userdisplay', $data); // Get the template userdisplay and pass data
This gets the data from the model, and then assigns it to a key within the "data" variable. You can then pass the data variable into the template. You'll then have two variables to work with in the template, $users and $posts.
You'll need a "getTemplate" function that properly maps the data array to individual variables for use in the template, but all of the display should be located in the template.
To answer your specific question at the end, something like this should work in the template:
if (count($users) > 0) {
foreach ($users as $person) {
echo $person['email'];
}
}
You should be able to do this:
foreach($output as $row) {
echo $row['email'];
}
I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.