i am newer to cakephp. i am trying to write a function which not regarding to view(function). but when i call this function resultCall to undefined function. my code is below
public function records(){
$totalrec = $this->names->find('count');
$pages = ceil($totalrec/$limit);
return $pages;
}
and call it as
$rowsr = records();
please help
Where are you defining and using this function?
If you want to use it absolutely everywhere, define it in the bootstrap-file in config. But be aware that this heavily violates MVC.
Looking at the function, I would guess that you probably want to add this function to the names model. Than you can call it from the Controller this way: $this->Names->records() and in the model this way: $this->records().
actually i was searching for this.
$this->records();
this is working.
Thanks all friends.
Related
I've done a search into stackoverflow but couldn't find anything.
Actually I'm working into recodding a "dirty" code done by a dev in a CakePHP 2.3 framework.
I'm not a dev myself, i'm more like a Swiss knife, i do some php but this is usually not my daily task.
:)
Let's go to the facts, i've got a controller with functions, and some functions under these functions...
Ex :
tool_controller.php
function addSomething(){
print_r($this->loadModel("db")); //it works // returns 1
function anotherFunction(){
print_r($this->loadModel("db")); //returns "Using $this when not in object context"
}
}
I'm a bit lost, searched in CakePHP docs but couldn't find anything either.
Can someone please help ?
thanks
This code would most probably be better written like this:-
public function addSomething(){
print_r($this->loadModel("db"));
$this->_anotherFunction();
}
protected function _anotherFunction(){
print_r($this->loadModel("db"));
}
I doubt you really need to nest functions for what you want to achieve. The above code should be simpler to read and is more obvious what context $this refers to.
OK people, i've solved my problem, as I told before the main function is an action after a submit, then I had a loop inside this function to treat the datas.
As i'm working in CakePHP and using the integrated functions (in this case the function "loadModel" in the "Controller" class), i had to get this function working in the nested function.
The solution was the following :
function addSomething(){
my_code_here
function anotherFunction(){
$controller = new Controller; // Had to redeclare the class
print_r($controller->loadModel("db")); // Works just fine
}
}
Thanks to all for your submissions.
Kind regards folks ;)
After that many of you suggest me to not to nest functions, I've decided to follow your advice and I've putted outside my main function, after I call back my function.
Public Function loopAction(){
//Code here
}
Public Function addsomething(){
//Code here
$this->loopAction();
}
It works perfectly and even better than before, thanks to all.
I would like to have shared function for all extended controllers which print give json object as response.
I placed this shared function into the "AppContoller.php" as static function.
Problem is that i cannot access to this-> in AppController.
Question is:
How can i solve it?
Here is the code of the function:
public static function printJsonOutput($responseData)
{
$this->RequestHandler->respondAs('json');
$this->autoRender = false;
echo json_encode($responseData);
}
Thanks for any help.
Read the book about json and XML views.
What you want to do is explained there in great detail, with code examples and shown the right way to do it.
What you do is wrong and like #Nunser already pointed out you don't have access to $this in a static function. You might want to do some OOP tutorial for php first?
I am modifying my PHP framework and trying to figure out an easier way to deal with different request types.
Currently I have this block in a controller method
$methodHandler = self::getMethodHandler(__FUNCTION__);
$this->$methodHandler();
Where getMethodHandler is
protected static function getMethodHandler($function) {
return $function."_".ucwords(strtolower(Request::getMethod()));
}
Ideally I want to reduce that two lines into one but PHP ain't having it
$this->self::getMethodHandler(__FUNCTION__)();
Anyway I could do this?
This should work:
$this->{self::getMethodHandler(__FUNCTION__)}();
That will evaluate self::getMethodHandler(__FUNCTION__) and call the result as a method of $this.
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?
In my codeigniter project I have
<?php
class User_model extends Model {
function user_model()
{
parent::Model();
}
// should we use instance method?
function get_total_users_count(){
$results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");
if($results){
return $results->num_rows();
}
return 0;
}
// or class method?
public static function get_total_users_count(){
$obj =& get_instance();
$results = $obj->db->query("SELECT * FROM bhr_users GROUP BY userid");
if($results){
return $results->num_rows();
}
return 0;
}
}
?>
I feel like this should be a class level method because it operates on multiple users. Do you agree? Is get_instance the proper way to do this in codeigniter?
Honestly, I don't think there's one right way for this. I'd say the instance method is the most common way, but that's not to say that it's right or wrong.
One big difference between CodeIgniter and some other frameworks is that models can be whatever you want them to be. According to the CI manual "The Model represents your data structures." it than says that models will "typically" interact with your database.
I like the loose definition that CodeIgniter uses for models, because it allows me to create models for dealing with any dataset. Want to use an RSS feed as a data source? You could use a model for that. Want to pull data from a webservice? You could use a model for that. You have the freedom to define how you use models.
I'd say the most important thing is consistency. Choose one method and use it consistently throughout your project. If you're working with other developers on the project, it may be better to use the instance methods. That way they won't get confused about what's going on when they compare working code on your site to the CodeIgniter documentation. That, of course, depends on the skill level of the devs you work with.
To answer your question directly - the get_instance() function call is the proper way to do what you're trying to do from within a static function.
You should be using
$results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");
Unless you are getting an instance of another class, you should do it this way.