calling another php function after jquery post - php

I am performing the jquery POST correctly, however I would like to call another PHP function inside the controller. EDIT The code below works fine....I'm just an idiot. Someone close this please.
Here is the setup:
class controller extends CI_Controller {
function con1() {
//retrieve post variable
$this->con2()
}
function con2() {
//do something
$this->my_model->get_results() //fails
}
}
Jquery POSTS to con1, however it will fail when i do $this->con2(). Is there anyway I can get this to work? Also, is it possible to call a model once jquery posts the data?
Thanks

It's not really clear what you aren't able to do, but why are you juggling with controller's methods, when model are done just for that?
The purpose of a Model is being something re-usable, so why don't you call it right in con1() method?
class Controller extends CI_Controller {
function con1() {
$this->load->model('my_model');
//retrieve post variable
echo $this->my_model->get_results();
}
}
Also, post variable are available to Models also, if you want to grab their values there.
If you expand your answer with further details I'll edit and update my question, so far it's just a bit of a guessing on what's wrong. The code I showed should work, provided the get_result() method actually returns something (which you need to echo out).
If by "how do I call a function within a model" means how you call a model's method inside another model's method, well, it works like any php class method's call, $this->other_method();

Haven't used codeigniter but I suspect redirecting to con2 within con1 with the post array would fix the issue.

Related

Can I call controller and model from view?

I have a problem with PHP/MVC.
This is my index controller.
<?php
class Index extends Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->view->render('header');
$this->view->render('index/index');
$this->view->render('footer');
}
public function test(){
$this->model->test();
}
?>
And this, index model.
<?php
class Index_Model extends Model{
public function __construct() {
parent::__construct();
}
public function test() {
return $this->db->select('SELECT text FROM test');
}
}
}
How can I use this in "index view"?
Of course you can call controller and model methods from your views (if it wasn't possible then you'd need to put EVERYTHING in your view). The idea of MVC isn't complete separation (as some people wrongly think) but separation of the logic. This means that it is fine to pass data between the different parts of the MVC arch; the idea is that you want to try to make sure that the logic in each part is logic that is appropriate for that part.
Many people will over complicate this in search of some ideal which is just silly. I would get rid of the controller method all together and reference the model method directly in the view if all you are doing is grabbing some data to be displayed in the view. There is no reason to waste time and effort passing these results to the controller just to be passed back to the view. You will thank me for this advice once you make a truly large site and look at all of the effort you would have spent doing that (and then later maintaining all of it).
My philosophy is that a controller should be used for just that (controlling the application logic). If you want to display a sidebar with a list of the most recent post that has NOTHING to do with the controller so it shouldn't add any code to it. Save yourself some headache and call the model from the view. In the end your code is going to make more sense if you do.
In response to your question: You cannot use your controller method in the view because it doesn't return anything.

MVC pattern (need view object in model)

I'm using the MVC pattern in my application.
Now I need the view object in a model.
I don't want to add the view as a parameter for my function in the model (since I need it in other functions as well). And I don't want to keep on passing it.
Should a add the view as an attribute for the constructor of the model?
Is there another way? Shouldn't I be needing the view object in the model in the first place?
What would be the preferred way of doing it?
Example:
Controller
function someAction()
{
$somemodel->add();
}
Model
class SomeModel()
{
function add()
{
if ($view->user) {
// do stuff
$this->mail();
} else {
// do other stuff
}
}
function mail()
{
Mailer::send($view->user->email, $this->getitems(), $view->layout);
}
function getitems()
{
return Items::getitems($view->user);
}
}
If you're really doing MVC, then you won't need the view in the model, because only the controller should have access to the view.
Looking at the code you've provided, I can tell one thing: the add() method should not reference $view in any way (even for accessing its properties). Instead, the model should be provided with the $view->user value from the controller. The same goes for the mail() method.
Consider fixing those issues. Otherwise, you'll get into something worse later on.
The model should be separate from the view. So, as mkArtak said, the controller should be the only thing that communicates with the view. Which then passes only the necessary information to the model.
As for the model, it should really only deal with the information that it understands.
i.e. if you had a Car model... you don't want to build it dependent on it's factory. If you did, you would have to change your code if you wanted to build it in different factory.
The controller is where you 'bake' everything prepare for render. By bake I mean you consider any passed in $_REQUEST params, make model API calls to get the data you need, and set template variables to be rendered. Your action, at the end of this process should make a call to a template (view) you choose in order to render the 'baked' template variables.

Can a site user pass their own arguments to model functions?

Are functions inside of models directly accessible by users?
Can a user pass arguments directly to a function in a model? Or, do arguments have to be passed through php?
In otherwords:
I have a model called notifications and in there a function called get_notifs($user)... I use the controller to call the function like the get_notifs($_SESSION['user_id']) (which is encrypted). I don't want someone to be able to call get_notifs() with anything but their $_session as a argument. What is the best solution?
Am I already okay?
Should I rename get_notifs() to
_get_notifs()?
Should I check the
$_SESSION['user_id'] in the method
itself?
Or, is there another better solution
than any of these?
I have a controller: ajax.php which loads the model notification
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('tank_auth');
$this->load->model('notification');
$this->load->model('search');
}
function get_notifs()
{
$me = $this->session->userdata('user_id');
if ($e = $this->notification->get_notif($me))
{
...........
}
else{
echo "nothing was found wtf?";
}
.........................................................
model: notification.php
function get_notifs($user){
......
}
Your code is perfectly fine!
Am I already okay?
I Think so
Should I rename get_notifs() to _get_notifs()?
No, it's a public method so no need to make it look private.
Should I check the $_SESSION['user_id'] in the method itself?
No, this is the controller's job
Or, is there another better solution than any of these?
You only need a solution to a problem, and i don't see a problem here
it sounds liek your application may be used by people other then yourself, i.e the public developers, why would you want enforce developers to code things your way, that's going to make them upset at your application.
CI Only routes requests to a controller, the user cannot access a model or library or any other class, the route goes like so: /controller/method/param
the first segment will only ever load a controller file, the second will call the method in the param, passing any other variables such as param to that method.
Source: http://codeigniter.com/user_guide/overview/appflow.html
As you can see from the flow chart above, only the controller has access to the model's
If you'll only use it while in a session the best way would be this:
function get_notifs(){
if(!isset($_SESSION['user_id'])){
return false;
}
$user = $_SESSION['user_id'];
/* Your code here */
}
There's no point of requiring an argument when you'll only use the function with one specific variable which is also available globaly.
Edit: I don't know why you're using functions in your models. Doesn't make any sense, do you mean methods?

codeigniter and OOP general question regarding calling functions, and the parent constuctor

Ok so I have some gaps in my understanding of PHP OOP, classes and functions specifically, this whole constructor class deal. I use both Zend and CI but right now Im trying to figure this out in CI as it is less complicated.
So all Im trying to do is understand how to call a function from a view page in code igniter. I understand that might go against MVC but Im working with an api and search results not from my database, so basically, I want to define a function in my class that I am able to call in one of my view pages.. and I keep getting "Fatal error: Call to undefined function functionname" error no matter what I try.
I thought I just had to declare
public function testing() {
echo "testing testing 123;
}
but calling that from the view I get that error. Then I read something about having to go
parent::Controller();
in the index of the class where the testing function also resides? But that didnt work either. Anyways, ya, can someone explain what I need to do in order to call the "testing()" function on one of my view pages? and clarification on the constructor class and what exactly parent::Controller() even does, would be much appreciated as well.
Like you said, that goes against the concept of MVC, so a better bet would be to use a helper function instead of declaring it as a controller method. Or, even better, let your controller deal with all the search API stuff, then pass the search results from your controller to your view.
I agree with both those points, but there are instances where you don't get the data you need until the view has been loaded (e.g. like some php data inside inline javascript or something).
If that's the case, I'd use an ajax call (within the view) to hit a function in the controller (since you just need a url to call them) and send along post data if the function needs to be fed anything. Does that make sense?
Yeah, like you said, that goes against the concept of MVC, but nothing is impossible. We can make it simply and follow the CI concept. You just need to pass a Controller object to the view:
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function sayhi() {
echo "Hi from controller...";
}
public function index() {
$this->load->view('test', array('controller' => $this));
}
}
Then you can call function defined at the controller, for example I called sayhi() from my view page:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h2>
<?= $controller->sayhi() ?>
</h2>
</body>
</html>

Passing parameters to controller's constructor

I have a controller which has several methods which should all share common informations. Let's say my URI format is like this:
http://server/users/id/admin/index
http://server/users/id/admin/new
http://server/users/id/admin/list
http://server/users/id/admin/delete
I need to retrieve some informations from the database for id and have them available for all methods instead of writing a line in each of them to call the model. How can I do this?
class users extends Controller {
private $mydata = array();
function users()
{
parent::Controller();
....
$this->mydata = $this->model->get_stuff($this->uri->segment(2));
}
function index()
{
$this->mydata; //hello data!
}
Here I simply hardcoded the array (which probably is a really bad idea). Nevertheless you can store the data in a codeigniter session if you need to. Codeigniter can store this data in a cookie (if it's total is less than 4kb) otherwise you can store bigger blobs of data in the database (see the docs on how to do this).
See: http://codeigniter.com/user_guide/libraries/sessions.html
Subsection: Saving Session Data to a Database
Here's some session exercise:
$this->session->set_userdata('mydata', $mydata);
....
$mydata = $this->session->userdata('mydata');
If this cannot be solved from CodeIgniters Hook mechanism, you could override the constructor method in your controller and call your own. Judging from their SVN repository you'd probably would do something like
class YourController extends Controller
{
function YourController()
{
parent::Controller();
$this->_preDispatch();
}
function _preDispatch()
{
// any code you want to run before the controller action is called
}
Might be that the call to preDispatch has to be before the call to parent. Just try it and see if it works. I didnt know they still use PHP4 syntax. Ugh :(
Based on your url structure, and the fact that codeignitor uses a MVC pattern, I'm assuming you're using mod_rewrite to format the url path into a query string for index.php. If this is the case, the value of "id" should be available at $_REQUEST['id'] at any point in the execution of the script...

Categories