codeigniter, library or helper can access through url? - php

In Codeigniter, there are library and helper.
I can access controller and its sub function.
for eample.
login/getid
Is there any way to access library or helper through url?
Update :
I made a captcha library in login controller.
I want to use it in many other controller's view.
in view file, the captcha code should be like this,
<img src="/login/get_captcha" />
everytime I want to use captcha, I have to call login controller.
So, I thought that there should be better way to do this.
If library or helper can access through url, I can make this to helper.
can access another controller's view without loading login's controller.

You can create a wrapper controller to access those functions exclusively and use your routes to utilize said URL's
Example: yoursite.com/helper/geo/citiesNearZip/90210
class helperController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper($this->uri->segment(1)); // geo helper in this example
if($this->uri->segment(2))
{
$helper_method = $this->uri->segment(2);
}
else
{
show_404();
return false;
}
// check if helper has function named after segment 2, function citiesNearZip($zip) in this example...
if(function_exists($helper_method)
{
// Execute function with provided uri params, xss filter, secure, etc...
// You would also want to grab all the remaining uri params and pass them as
// arguments to your helper function
$helper_method();
}
}
}

Nope. This is simply not the way the framework was designed to work.
If you think you have to access a helper/library directly, then you're probably doing something wrong.
Can explain what you're trying to do? There must be a better way.

Related

Run a method before any other method in a CodeIgniter controller

In CakePHP we have beforeFilter and afterFilter to run methods before or after any controller methods (e.g. save log or check logged in etc.)
How can I do this in CodeIgniter?
You'll want to make use of hooks in Codeigniter, that is where they have implemented your desired functionality of running code before certain points of the framework code.
https://www.codeigniter.com/user_guide/general/hooks.html
There are some built-in hooks that allow you to call a method or class at various points during the request:
pre_system
pre_controller
post_controller_constructor
post_controller
display_override
cache_override
post_system
So what you want is probably something like pre_system or pre_controller.
Check out the _remap() function. It allows you to redirect to your own function before calling the normal controller function. You can include your own _remap function in your controller like this (copied from the User Guide):
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
The second segment of the URI gets passed to the _remap function as a parameter (in the example as $method), and you can then redirect the process however you need.

Zend Framework: add data to layout for every action of controller

i am writing a web application and i need all the data returned/computed in all actions of one specific controller to return data to the layout (not the view).
So after each action, a controller variable needs to be passed to the layout so the layout can use it.
In detail, i want to store the calculated data in jSon in the head.
Any ideas anyone of how to do this?
I thought about a controller plugin but i have no idea of how to access the desired parameters then and i really don't want to use a singleton for all this.
Let use, this method is executed before every action
public function preDispatch() {
}
for example
public function preDispatch()
{
//calculate something
//this is an example
if($this->getRequest()->getActionName()=="admin")
{
$this->_helper->layout->setLayout('admin');
}
else
{
$this->_helper->layout->setLayout('user');
}
}

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?

CakePHP: Accessing the controller or model from a view helper

I have a view helper that manages generating thumbnails for images. The images are stored using a unique ID and then linked to a file resource in the database.
I am trying to find out if it is possible for the view helper that generates these images to access the model or controller directly, as it is not possible to load the image data at any other point in the controller work flow.
I know this is a bit of a hack really, but it is easier than trying to rebuild the entire data management stack above the view.
If you had set the data in the model or controller you could access it. So you'd have to think ahead in the controller. As you said you can't load it in the controller, perhaps you need to write a specific controller function, which you can call from the view using $this->requestAction() and pass in the image name or similar as a parameter.
The only disadvantage of this is using requestAction() is frowned upon, as it initiates an entirely new dispatch cycle, which can slow down your app a bit.
The other option, which may work is creating a dynamic element and passing in a parameter into the element and have it create the image for you. Although I'm not too sure how this would work in practise.
How are you generating the thumbnails using the helper in the view if you aren't passing data into it from a controller or model? I mean if it was me, I would be setting the 'database resource' in the controller, and passing it to the view that way, then having the helper deal with it in the view. That way you could bypass this issue entirely :)
$this->params['controller'] will return what you want.
According to the ... you can put this code in a view.ctp file then open the URL to render the debug info:
$cn = get_class($this);
$cm = get_class_methods($cn);
print_r($cm);
die();
You could write a helper and build in a static function setController() and pass the reference in through as a parameter and then store it in a static variable in your helper class:
class FancyHelper extends FormHelper {
static $controller;
public static function setController($controller) {
self::$controller = $controller;
}
... more stuff
}
Then in your Controller class you could import the FancyHelper class and make the static assignment in the beforeFilter function:
App::uses('FancyHelper', 'View/Helper');
class FancyController extends AppController {
public $helpers = array('Fancy');
function beforeFilter() {
FancyHelper::setController($this);
}
... more stuff
}
And then you could access the controller from other public functions inside FancyHelper using self::$controller.
You can check the code(line ☛366 and
line ☛379) of the FormHelper, try with:
echo $this->request->params['controller'];
echo Inflector::underscore($this->viewPath);

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