Functions in Controllers (beginner) |
[eluser]Michal1[/eluser]
Hello, I am still trying to figure out in my head, how exactly functions works in Controllers. I understand that function index () is always the function which is called when exact controller is loaded so for example if I have a controller site and inside this I have Code: function index() then when myadress.com/site is loaded I get this echo. But I do not understand an usage of other functions in controller. Lets say I have this function also inside my site controller which communicates with model function which inserts some data into database: Code: function add_records() now I know that when I want to call this function i need to type this url: myadress.xxx/index.php/site/add_records And then it will work and data will be inserted into database. However in this case it is useless, because I need to use this function when index of site controller is used. So I know I could take the whole code from add_records() and insert it into index() function. But then when I have more lines of code, it would be kinda confused and I would get lost easily in a future. So what I am trying to realise is, what is the right approach for this? I am pretty sure I am missing something. I would want to have something, that I could use a function add_records() in function index() so data will be inserted when index is called. Or do I get it wrong and calling it exactly in index function is the only way? I am sorry for hard explaining, however I just like to thinkg about everything to understand how does it exactly work :-)
[eluser]Atharva[/eluser]
Code: function index() This will do your job.
[eluser]Michal1[/eluser]
Ah I am stupid, thanks :-) Just a question, is it a right approach? Or you would not advice me this.
[eluser]Akinzekeel[/eluser]
Just like in any other object you can call methods like this: Code: $this->add_records() Since you probably don't want anyone to simply call the add_records() method via URL, I suggest you should make it private like this: Code: private function add_records() { ... } So http://example.com/example_controller/add_records will result in a 404 Not Found error.
[eluser]Atharva[/eluser]
[quote author="Michal1" date="1295026492"]Ah I am stupid, thanks :-) Just a question, is it a right approach? Or you would not advice me this.[/quote] As mentioned by sHiRoKKo1337, you can make the function private, and making it dynamic by passing it $first_name and $last_name. But if function index is doing nothing, then why not to have insert code and view loading in that function? Also, you don't want insert static values, I am sure you will have form, validation rules etc. So it really depends on the situation and choice.
[eluser]Michal1[/eluser]
Thank you very much much guys. It is a good point with private function. This is such a helpful forum :-) |
Welcome Guest, Not a member yet? Register Sign In |