Here's the thing:
I loaded the model in the constructor method. Supposedly, I could use it on all the methods inside that controller, but I can only access it properly from the index method. When I used the loaded model in a different method - same controller, it gave me an error could not get function of non-object. I can use it on index() but why not on other methods inside the same controller? I loaded the same model on different controller and it works fine. I checked my controllers to see if there's any difference between the two and make sure that they're the same - in term of syntax and such, and they're the same.
Another is that I loaded another model, used it and worked fine, it inserts, create, etc but when I used the controller method to throw a json_encoded array back to the view because I used $.ajax on that, it gives me responseText - a string not a json - and it goes directly to error function of the $.ajax. I removed the model and the $.ajaxtriggered its success function.
I don't know where's the problem here. Also it happens to not just one model and comtrollers
Related
I am using Laravel 7.x, I have a controller which when called in the routes, instead of loading its own called method, will rather load the method of a different controller, I don't know how and why?
I.e. Controller-A executes Controller-B methods which was not called.
So, I am calling the route below from my web.php directory.
Route::get('/testx', 'ControllerA#show_table');
but it loads another ControllerB's method instead thereby loading the wrong route. Does laravel cache controllers? Its a strange logic error to me.
Thank you guys for your response. I finally solved the problem.
I had earlier saved a controller with the same class as the current controller while running a test, and forgot to remove it from the controller directory, this was the cause of error "Duplicate Class" in the same namespace. I simply removed the duplicate class controller and the issue was resolved.
In a custom validation function in my model class. I need to use javascript code. for that i used registerJs function but i am getting error:-
Calling to undefined function registerJs()
I also tried calling it by including View class i.e., View::registerJs() but it is also giving error called
Non-static method yii\web\View::registerJs() should not be called statically, assuming $this from incompatible context
How can i user Javascript in Yii2 model class.
Edit:
I have created a custom function for mobile number validation and calling that function from rules section of model. Now i want to use javascript code in that function. is there any other way to achive it?
Thanks in advance
That method is not static. If you open the view.php of the framework you can check out the implementation.
public function registerJs($js, $position = self::POS_READY, $key = null){..
}
Exception clearly mentions that should not be called statically because it is not declared static.
I have seen few of the implementations which call this method as:
$view->registerJs($js, $view::POS_END);
Basically loading a particular JS file in one of the functions.
It is not a good idea using Javascript with a model. If you go that way then probably after some time you will find you heading into big problems with the architecture of the app.
The best way is to call the model inside a controller and then interact with the controller through the Javascript code.
This might be a bit hard to comprehend so I apologize in advance if this is not clear enough.
I'm writing my own MVC framework and am once again stuck.
I am in the process of writing the controller classes for the framework. Basically this is how it works:
Instantiate class coreController which extends abstract class
coreController sets controller to be loaded by interpreting query string
query string values stored in variables
other variables assigned values
new controller is loaded
new controller checks if an action object needs to be instantiated.
new actioncontroller is loaded
action controller checks if it is the final object required.
action controller is returned as an object to be referenced during the rest of the script.
generic $controller->method() can be called and references final controller loaded.
Another overview:
coreController
pageController
pageControllerActionAdd
return as object to start
$controller->something(); //References pageControllerActionAdd
Esentially what I want to be able to do is be able enter a url like:
http://www.mywebsite.com/page/modify/
and have the script pull up the PageModifyController as a variable so I can execute it's methods.
If you can tell me a better method for what I am doing please go ahead. You don't have to write any code, just the idea would be great. It is just that the way I am currently doing is very confusing and hard to debug. I will end up with multiple nested objects and I don't like the concept of that.
I've been reading a lot of other source code and found that it too can be quite sophisticated.
I actually created a framework that works along the lines you are trying to implement. I think what you are missing is a RoutingHandler class. Routing is the physical manipulation of the URL, which tells your application which Controller to load, and which Action to run.
In my world I also have Modules, so the basic routing scheme is
Module -> Controller -> Action
These three items map to my URI scheme in that fashion. Variables can be appended also like so...
http://www.domain.com/module/controller/action/var1/val1/var2/val2
So, what happens after the URI is parsed, and control is passed over to the appropriate controller and action? Let's make some code up to demonstrate a simple example...
<?php
class indexController extends Controller {
protected function Initialize() {
$this->objHomeModel = new HomeModel;
$this->objHeader = new Header();
$this->objFooter = new Footer();
$this->objHeader
->SetPageId('home');
}
public function indexAction() {
$this->objHeader->SetPageTitle('This is my page title.');
}
// other actions and/or helper methods...
}
?>
In the Initialize method, I'm setting some controller-wide stuff, and grabbing an instance of my Model to use later. The real meat is in the indexAction method. This is where you would set up stuff to use in your View. For example...
public function randomAction() {
$this->_CONTROL->Append($intSomeVar, 42);
}
_CONTROL is an array of values that I manipulate and pass onto the View. The Controller class knows how to find the right template for the View because it is named after the Action (and in a sibling directory).
The Controller parent class takes the name of the action method and parses it like so...
indexAction -> index.tpl.php
You can also do some other fun stuff here, for example...
Application::SetNoRender();
...would tell the Controller not to render inside a template, but just complete the method. This is useful for those situations where you don't actually want to output anything.
Lastly, all of the controllers, models, and views live inside their own Module directory like so...
my_module
controllers
indexController.class.php
someotherController.class.php
:
:
models
HomeModel.class.php
:
:
templates
index.tpl.php
someother.tpl.php
:
:
I can have as many Modules as I need, which means I can separate functionality out by Module and/or Controller.
I could go on, but I'm writing this from memory, and there are some wrinkles here and there, but hopefully this gives you food for thought.
I have 2 controllers: UsersController and AnalyticsController.
When I run:
//UsersController:
function dummyFunction(){
$this->Analytic->_loadChartFromId($chart_id);
}
the output is:
Query: _loadChartFromId
Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '_loadChartFromId' at line 1 [CORE\cake\libs\model\datasources\dbo_source.php, line 684]
The _loadChartFromId() function takes $chart_id as an argument and returns an array as output. I have no idea why Query: _loadChartFromId appears.
You don't call other controller methods from your controller.
In your users controller, $this->Analytic is an instance of the Analytic model, not the AnalyticsController. So CakePHP thinks you are trying to call a public method called _loadChartFromId() on the Analytic model, which, as you know, doesn't exist.
The reason you get the error is because if you try to call a non-existent method of a model, CakePHP tries to convert it to one of its Magic Find Types. Of course, it's not a valid Magic Find Type either, so you get a SQL error.
Solution
It's difficult to provide a complete solution as we only have part of your code, but you are perhaps violating the concept of MVC with the way you're coding your app.
You need to do one of two things:
Move _loadChartFromId() to your users controller. This seems to me like it would be counter-intuitive, as it probably has nothing to do with the User.
Move the method to your Analytic model. You would need to make it public so the controller can access it, and in your users controller you would need to make sure you have the Analytic model loaded.
class Analytic extends AppModel {
public function _loadChartFromId($chart_id) {
// ...
}
}
Then you can call the method as you were doing before, from your users controller.
I could have opted to close this question as an exact duplicate of at least 5 other questions (if you search for "cakephp another controller").
But the answers there are just terrible. They actually try to invoke new Dispatchers or requestAction().
So if your question is about another controller method:
The short answer is: You don't.
The long answer: You still dont. That's a typical beginners mistake.
You should put the functionality into a component if it is mainly business logic. The component then can be accessed from multiple controllers.
If it is more like model data (as in your example), put the functionality into the model layer (in an appropriate model). this way you can also access it from anywhere in your application.
Also: Accessing protected methods from other objects is never a good idea. Use public methods if you intend to use it from "outside" the object.
If your question is about a model method:
You need to include your model in your controller before you can use it.
Either by using public $uses or by using loadModel('ModelName') or even ClassRegistry::init('ModelName').
can anyone tell me how do i access model from view in codeigniter?
Load a model on the controller
$this->load->model('yourmodel');
Assign this model to a var like this
$data['model_obj'] = $this->yourmodel;
and assign this data array to your view template
Use $model_obj object on the view template for calling model methods
$model_obj->some_method()
Hope this helps ...
See the thread:
View Calling a Model
By the way why do you need to access the model from the view, you can send the model data to the view from the controller too which is the usual and better approach.
As a good note, keep your processing logic out of the view, you should use controller instead.
CodeIgniter's $this->load->model() returns absolutely nothing. Look at it: system/libraries/Loader.php.
This will output absolutely nothing:
$model = $this->load->model('table');
print_r($model);
And this next example will give you the fatal error Call to a member function some_func() on a non-object:
$model = $this->load->model('table');
$model->some_func();
It doesn't matter whether that function even exists, $model is not an object.
The thing to do is have a method in your model that returns data, then call that function and pass the results to your view file:
$this->load->model('table');
$data = $this->table->some_func();
$this->load->view('view', $data);
PS: How is the only answer you've accepted the absolute wrong thing to do?
You can use following code:
$ci = &get_instance();
$ci->load->model('your_model');
$ci->your_model->your_function();
Note: You have to call your model in your controller. Its working fine
In cases when you want to access a model function from within a shared view , you don't have to load the needed model in every controller that will call that view. you can load the model inside the view itself by using the following code :
$ci =&get_instance();
$ci->load->model(model_name);
$ci->model_name->function_name();
in older versions of codeigniter the following code used to work :
$this->load->model('model_name');
model_name::function();
but when tested on CI 3.1.9 it throw the following error
Message: Undefined property: CI_Loader::$model_name_model
Note: I use this technique in template views (sidebar, menus ...etc) which is not used everywhere in my application , if you want to access a model from anywhere in your application considre loading this model globally by adding it to the autoload array in application/config/autoload.php
Since $model is not an object, you can make a call to the model "table" using "::" scope resolution operator, which can call the function of the class itself without any object instance.
$this->load->model('table');
table::some_funct();
Note: you also need to make the function "some_funct" static inside your model "table".
Hey. You can access from view to models the same mode as you access on its controller. Remember that the view access to models that import its controller.
in the original UML I've seem for MVC architecture, view calls methods in model..
http://www.as3dp.com/wp-content/uploads/2010/02/mvc_pope_krasner.png
..but in practice with PHP apps, because there is no persistence to track state changes in objects between requests (or at least not efficiently), I find it better to keep all model method calls in controller and pass the result to view if possible.
you can add your model's name to config -> autoload model
$autoload['model'] = array('model_name');
this success for me
You can access basicly a method from view in codeingiter.
public function index()
{
$this->load->model('persons');
$data['mydata'] = $this->persons->getAllSessionData();
$this->load->view('test_page', $data);
}
in view
print_r ($mydata);
my function returned an array.