How to reload a library in Codeigniter? - codeigniter

*library is calling from 2 functions. when I call it second time it pick the data of first function. I want to reload the library in second function.
public function impnewsdetail($ref) {
$url = array(
'base' => $ref,
'category' => ""
);
$this->load->library('crawler', $url);
$nd = $this->crawler->getNewsDetail();
$newsdetail = array(
'detail_heading' => $nd['detail_heading'],
'detail_tags' => $nd['detail_tags'],
'detail_date' => $nd['detail_date'],
'detail_image' => $nd['detail_image'],
'detail_image_detail' => $nd['detail_image_detail'],
'detail_text' => $nd['detail_text']
);
return $newsdetail;
}

If You don't wish to set different library names (as #mic suggests), You can unset the library to force the Loader to load again with another config:
$this->load->library ('crawler', $url_1);
unset ($this->crawler);
$this->load->library ('crawler', $url_2);

Try this I am not sure..
$this->load->library('crawler');
$mylib= new Mylib($url);
$mylib->somemethod();

maybe you could set a unique name for the object you are loading. This can be done like this:
function method1()
{
$this->load->library('crawler', $url, 'crawler1');
$this->crawler1->method();
}
function method2()
{
$this->load->library('crawler', $url, 'crawler2');
$this->crawler2->method();
}
Now each instance of it will be unique.
I hope this helps, Good Luck

Maybe someone will find this question, here is my solution:
you can define new method in your library with will change your library' option:
Example - In your library define:
function __construct($initParams = array())
{
//..somecode
// init option here
//........
// end init
}
//add this function to re-config:
function reloadConfig($initParams){
//simple re-call init option code
// init option here
//........
// end init
}
In Use:
$this->load->library ('crawler', $option1);
//and when want to change option:
$this->crawler->reloadConfig($option2);

Related

How to change value of a request parameter in laravel

I need to change value of my request parameter like this:
$request->name = "My Value!";
I use this code but does not work:
$request->offsetSet('img', $img);
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to #JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request
Use merge():
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all() to another variable.
Read more about Laravel's merge() here:
https://laravel.com/docs/collections#method-merge
If you need to customize the request
$data = $request->all();
you can pass the name of the field and the value
$data['product_ref_code'] = 1650;
and finally pass the new request
$last = Product::create($data);
If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);
Use add
$request->request->add(['img' => $img]);
If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().
namespace App\Http\Requests\Admin\Category;
class CategoryRequest extends AbstractRequest
{
protected function prepareForValidation()
{
if ( ! $this->get('url')) {
$this->merge([
'url' => $this->get('name'),
]);
}
$this->merge([
'url' => \Str::slug($this->get('url')),
'active' => (int)$this->get('active'),
]);
}
}
I hope this information will be useful to somebody.
It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2
Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);
Try that :
$request["name"] = "My New Value";
$request["img"] = $img;
It's worked in Laravel 8.
Also, make sure to update the model class.
Item
{
fillable=[
'img',
... // other attributes
];
}
in case of updating an item of object you can write the lines bellow
$Obj = $request->data;
$Obj['item'] = value;

ZF2 - Saving a result of a function in cache

I made a view helper that checks if an external URL exists before outputting it. Some of those URLs are in my main layout, so that check is quite slowing down my site by calling all those urls all the times, to check if they exist. I would like to save the output of that function so that it only checks an URL if the same one hasn't been checked already in less than an hour, or a day. I believe I should use Zend Cache to do that? But I have no idea where to start, do you have any suggestions, easy solutions or some basic tutorial to learn? Thanks!
Add global config for cache service, like here:
config/autoload/global.php
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
)
),
config/autoload/cache.global.php
return array(
'caches' => array(
// Cache config
)
)
Use factory to create your View Helper:
Application/Module.php::getViewHelperConfig()
'LinkHelper' => function ($sm) {
$locator = $sm->getServiceLocator();
return new LinkHelper($locator->get('memcached'))
}
Use cache service in your View Helper:
LinkHelper.php
protected $cache;
public function __construct($cache)
{
$this->cache = $cache;
}
public function __invoke($url)
{
$cacheKey = md5($url);
if ($this->cache->hasItem($cacheKey) {
return $this->cache->getItem($cacheKey);
}
$link = ''; // Parse link
$this->cache->setItem($cacheKey, $link);
return $link;
}

cannot set user data in session codeigniter

please look at this.
The code below is from my model class (using datamapper orm)
function login()
{
$u = new User();
$u->where('username', $this->username)->get();
$this->salt = $u->salt;
$this->validate()->get();
if (empty($this->id))
{
// Login failed, so set a custom error message
$this->error_message('login', 'Username or password invalid');
return FALSE;
}
else
{
// Login succeeded
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$this->session->set_userdata($data);
return TRUE;
}
}
when i do this i get
**Fatal error: Call to a member function set_userdata() on a non-object**
but when i do this instead
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$obj=& get_instance();
$obj->session->set_userdata($data);
It works.
Please what is the right way to get this working ?
Thanks in advance.
your model did not extends CI_Model
after that you have to add constructor to your model
add this code to yours
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Well, you didn't provide enough information.
The first code looks fine, provided that:
You actually load the session class before calling it (you also need to create an encryption key in your configs).
$this->load->library('session');
$this->session->set_userdata($data);
The above code, or your code, is inside a controller, a model or a view.
$this relates to the CI's superclass, in particular to an instance of the Session class, so if you're calling that inside a helper (collection of functions), or inside a library (where you need to create a CI instance first), it won't work.

load multiple models in array - codeigniter framework

<?php
class Home extends CI_Controller
{
public function __construct()
{
// load libraries //
$this->load->library('session');
$this->load->library('database');
$this->load->library('captcha');
// alternative
$this->load->library(array('session', 'database', 'captcha'));
// load models //
$this->load->model('menu_model', 'mmodel');
$this->load->model('user_model', 'umodel');
$this->load->model('admin_model', 'amodel');
// alternative
$this->load->model(array(?));
}
}
?>
How can i load all models in array? is it possible?
For models, you can do this:
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
foreach ($models as $file => $object_name)
{
$this->load->model($file, $object_name);
}
But as mentioned, you can create file application/core/MY_Loader.php and write your own method for loading models. I think this might work (not tested):
class MY_Loader extends CI_Loader {
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach ($model as $file => $object_name)
{
// Linear array was passed, be backwards compatible.
// CI already allows loading models as arrays, but does
// not accept the model name param, just the file name
if ( ! is_string($file))
{
$file = $object_name;
$object_name = NULL;
}
parent::model($file, $object_name);
}
return;
}
// Call the default method otherwise
parent::model($model, $name, $db_conn);
}
}
Usage with our variable from above:
$this->load->model($models);
You could also allow a separate DB connection to be passed in an array, but then you'd need to have a multidimensional array, and not the simple one we used. It's not too often you'll need to do that anyways.
I don't have any idea about the CodeIgniter 2.x but in CodeIgniter 3.x, this will also works :
$models = array(
'menu_model' => 'mmodel',
'user_model' => 'umodel',
'admin_model' => 'amodel',
);
$this->load->model($models);
Not natively, but you can easily extend Loader->model() to support that logic.
This work fine for me:
$this->load->model(array('menu_model'=>'menu','user_model'=>'user','admin_model'=>'admin'));

Calendar class in Codeigniter not showing next/previous months

I am trying to generate a calendar and almost have it, but when I click the next or previous links, the calendar is not displayed - otherwise it is correct. When I click the next url the address bar shows the correct url, but the next month is not shown.
Here is my code:
class Poll_controller1 extends skylark {
function poll_home()
{
$this->add_to_center(POLL,"poll_view1");
$this->load_lcr_template();
$prefs = array (
'show_next_prev' => TRUE,
'next_prev_url' => 'http://skylarkv2/index.php/poll_controller1/show'
);
$this->load->library('calendar', $prefs);
}
function show()
{
echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
}
Am I making mistake or missing something?
try this from controller
public function display($year = null, $month = null)
{
$config = array(
'show_next_prev' => 'TRUE',
'next_prev_url' => base_url().'calendarC/display'
);
$this->load->library('calendar', $config);
$data['calendar'] = $this->calendar->generate($year, $month);
$this->load->view('calendar', $data);
}
Most likely, you just need to initialize the calendar class in the same scope that you generate it. The way you have it set up, show() has no knowledge of how the class was initialized in poll_home(). Try something like this:
function show()
{
$prefs = array (
'show_next_prev' => TRUE,
'next_prev_url' => 'http://skylarkv2/index.php/poll_controller1/show'
);
$this->load->library('calendar', $prefs);
echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
}
There's also the chance that $this->uri->segment(3) and $this->uri->segment(4) are not what you think they are, double check that those values are correct. If you are have any routing going on, you may need to use $this->uri->rsegment() instead (note the r).

Resources