When calling a function within a class I am using something like this:
protected $_mdl = 'mdl_posts_latest';
function __construct()
{
parent::__construct();
$this->load->model($this->$_mdl);
}
public function index()
{
$offset = 0;
$limit = 5;
$data['p_latest'] = $this->mdl_posts_latest->get_posts_latest($offset, $limit);
...
...
...
.
and it is working.
The problem is when I ry something like:
$data['p_latest'] = $this->$this->$_mdl->get_posts_latest($offset, $limit);
It throws this error:
Object of class Posts_latest could not be converted to a string
because, obviously, this code is wrong: $this->$this->$_mdl->
So, my question is how can I define the name of my modeljust once at the top of my class and then use it as a variable within all calls for calling a function etc.
Because right now I don't know how to do it so it would look like something:
$this->$model->get_something();
When you're loading the model, you should access the member variable like this, without the $ preceding the member variable's name:
$this->load->model($this->_mdl);
You could look into PHP's variable variables and complex (curly) syntax. It would allow you do something like this, where you can use the value of the variable:
$this->{'_mdl'}->get_posts_latest($offset, $limit);
$this->load->model($_mdl);
instead of
$this->load->model($this->$_mdl);
then:
$data['p_latest'] = $this->$_mdl->get_posts_latest($offset, $limit);
or
$md1 = $this->$_md1;
$data['p_latest'] = $md1->get_posts_latest($offset, $limit);
Related
I have a question,
what does $page purpose in here?
public function user_defined($page = 'view_file.php')
{
#Syntax
}
is $page a user_define too or a fixed// function in CI?
Sorry if this has already an answer, I'm exploring CI
1) if you define parameterized function you have to pass the parameter like below
public function user_defined($page)
{
#Syntax
}
in this case if you call this function without parameter it will respond with fatal error.
2) If you define optional parameterized function you can pass parameter or not
public function user_defined($page = 'view_file.php')
{
#Syntax
}
in this case if you call this function without passing parameter it will respond without any error.
In one of projects i got recently have all the urls like
www.abc.com/controller/action/1222
I want to encrypt the url parameters only to achieve something like
www.abc.com/controller/action/saddsadad232dsdfo99jjdf
I know I can do it by changing all the urls one by one and sending the encrypted parameters and dealing with them all over the places in the project.
So my question is Is there a way I can encrypt all the urls at once without making changes to every link one by one ?
Just need a direction.I guess I put all the details needed.
thanks !
Here is a solution if you use the site_url helper function and you are sure that all your URLs comply this format www.abc.com/controller/action/1222:
All you need is to override the site_url method of the CI_Config class
class MY_Config extends CI_Config
{
public function site_url($uri = '', $protocol = NULL)
{
$urlPath = ltrim(parse_url($this->_uri_string($uri), PHP_URL_PATH), '/');
$segments = explode('/', $urlPath);
$numOfSegments = count($segments);
$result = [$segments[0], $segments[1]]; // controller and action
// start from the third segment
for($i = 2; $i < $numOfSegments; $i++)
{
// replace md5 with your encoding function
$result[] = md5($segments[$i]);
}
return parent::site_url($result, $protocol);
}
}
Example:
echo site_url('controller/action/1222'); will outputwww.abc.com/controller/action/3a029f04d76d32e79367c4b3255dda4d
I use a Hashids helper. I think this will do what you're after.
You can pass parameters to your functions like this:
base_url('account/profile/' . hashids_encrypt($this->user->id))
You can then decrypt it within the function and use it however you want:
$id = hashids_decrypt($id);
I'm trying to generate something like 6B6E23518 using randomString() which I'm calling inside my controller
function randomString($chars=10) //generate random string
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < $chars; $i++) {
$randstring .= $characters[rand(0, strlen($characters))];
}
return $randstring;
}
public function store(TicketsCreateRequest $request)
{
$ticket = $user->tickets()->create([
'ticket_hash' => $this->randomString(10),
// ....
]);
}
but this keeps on storing 0 into 'ticket_hash' and nothing gets generated??
Looking at your source code, is randomString() a public method of your controller class or is it a global function declared elsewhere outside of the class? I ask because it's entered above without the public visibility qualifier and with slightly different indentation to the method below it.
If this function is not an instanace method of your class, then your call to $this->randomString() is probably not calling the method you're expecting it to call. If your randomString() function is a global function defined elsewhere you should call it directly (eg. 'ticket_hash' => randomString(10),)
For what it's worth, for random strings like this it might be best to use the Laravel framework's Str class, only because it may be more stable and is definitely more widely used.
The Str::random() method achieves the output you're looking for in this case.
column ticket_hash was an integer type ,changed it to varchar and it works now.
Let's say I have a controller and I want to define some const variables that hold some messages (eg error messages etc).
Is there a way to make it so they are translated?
An example class is defined bellow:
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AccountController extends AbstractActionController
{
protected $testError = 'There was an error while testing some stuff';
public function testAction(){
// I know i can use the following approach but I don't want to
// since I want to use a variable for readability issues.
// $testError = $this->getTranslator()->translate('There was an error..');
return new ViewModel();
}
/**
* Retrieve the translator
*
* #return \Zend\I18n\Translator\Translator
*/
public function getTranslator()
{
if (!$this->translator) {
$this->setTranslator($this->getServiceLocator()->get('translator'));
}
return $this->translator;
}
/**
* Set the translator
*
* #param $translator
*/
public function setTranslator($translator)
{
$this->translator = $translator;
}
}
So I want to have the testError translated. I know I can just use the message and translate it via the zend translator without using a variable, but still I want to store it in a variable for readability issues. Any help or other approaches to this?
Simply create a translations.phtml file in any directory in your project root and fill it something like that:
<?php
// Colors
_('Black');
_('White');
_('Green');
_('Light Green');
_('Blue');
_('Orange');
_('Red');
_('Pink');
In poedit, check Catalog Properties > Source keywords list an be sure _ character is exists. (Alias of the gettext method). In application, use $this->translate($colorName) for example.
When poedit scanning your project directory to find the keywords which needs to be translated, translations.phtml file will be scanned too.
Another handy approach is using _ method (gettext alias) to improve code readability. Example:
$this->errorMsg = _('There was an error..');
But don't forget to set the global Locale object's default locale value too when you initialising your translator instance first time in a TranslatorServiceFactory or onBootstrap method of the module:
...
$translator = \Zend\Mvc\I18n\Translator\Translator::factory($config['translator']);
$locale = 'en_US';
$translator->setLocale($locale);
\Locale::setDefault($translator->getLocale());
return $translator;
...
I don't quite understand what you mean:
$errorMessage = 'FooBarBazBat";
return new ViewModel(array(
'error' => $this->getTranslator()->translate($errorMessage)
));
would be a way to store the message inside a variable. But i really don't understand where your problem is.
Or do you mean having the translator as variable?
$translator = $this->getServiceLocator()->get('viewhelpermanager')->get('translate');
$errorMessage = $translator('FooBarBazBat');
I have a function that needs to pull arguments from the URL like CI is supposed to do. But it's not doing it. My URL is domain.com/lasers/en/acme.
My class Lasers is:
class Lasers extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('products_model');
$this->load->model('common_model');
$this->load->model('select_country_model');
$this->load->model('markets_materials_model');
}
function index($lang = NULL, $laser = NULL)
{
$query = $this->products_model->get_product_content($laser, $lang);
}
The model is loaded in the constructor. The $lang I need is "en" and the $laser I need is "acme". So why isn't this working? The arguments in the function are in the correct order, so I can't see what's wrong.
By default you cant pass arguments to the index method of a controller
if you go to domain.com/lasers/en/acme it is looking in the lasers controller for a method called en.. (which doesn't exist) and trying to pass a single parameter of acme to it
Theres a few solutions, probly the easiest is to use a different method (not index) then use routes to make the URLs work.
add something like this to your config/routes.php
$route['^lasers/(:any)/(:any)'] = "lasers/get_products/$1/$2";
Then use a method like this instead of index:
function get_products($lang = NULL, $laser = NULL) {
$query = $this->products_model->get_product_content($laser, $lang);
}
.. OR you could use _remap to override the default behaviour
Does it work if you write "domain.com/lasers/index/en/acme"?
If you write domain.com/lasers/en/acme, it will look for the "En" function, $lang being "acme", and $laser remaining NULL.