<?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'));
Related
I want to add models from one table called "modellist" in middle of the program.
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2){
$model=TransactionModules::where('id',$info->module_id)->first();
$model_name=$model->model; // here am getting model name form table
use App\Models\.$model_name; //i used this function to include model on middle of program
$model_name::find($info->transaction_id)->update(['status' => 7]);
}
}
I have not tested this but try:
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2){
$model=TransactionModules::where('id',$info->module_id)->first();
($model::class)::find($info->transaction_id)->update(['status' => 7]);
}
}
The class method returns the namespace with model name
I hope this works
You can do this direct on eloquent.
no need to declare use first
remember to use namespace as a string => "App\Models\\"
foreach ($trans_infos as $key => $trans_info) {
if($trans_info->heirarchy_type==1 || $trans_info->heirarchy_type==2)
{
$model=TransactionModules::where('id',$info->module_id)->first();
"App\Models\\".$model->model::find($info->transaction_id)
->update(['status' => 7]);
}
}
I have a model that has a one to many relationship to the versions of the description.
In my Controller
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
]);
$tag->update([
'content' => $request->get('description')
]);
In my Model:
public function setContentAttribute(string $value)
{
$this->versions()->create([
'user_id' => \Auth::id(),
'value' => $value
]);
}
So I can't put content directly as an attribute in the create method because there is no Model right now.
But is it possible to overwrite the create Method?
When I try to overwrite something like this in my Model it will do an infinity loop
public static function create($attr) {
return parent::create($attr);
}
So my question is if it is possible to have something like this:
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
'content' => $request->get('content')
]);
and in the Model:
public static function create($attr) {
$value = $attr['content'];
$attr['content'] = null;
$object = parent::create($attr);
$object->content = $value;
$object->save();
return $object;
}
Update
I didn't overwrite the create method but called it customCreate. So there is no infinity loop anymore and I can pass all variables to the customCreate function that handles the relationships for me.
Solution
After reading the changes from 5.3 to 5.4 it turns out that the create method was moved so you don't have to call parent::create() anymore.
The final solution is:
public static function create($attr) {
$content = $attr['content'];
unset($attr['content']);
$element = static::query()->create($attr);
$element->content = $content;
$element->save();
return $element;
}
I don't see why not and you could probably implement a more general approach? Eg. checking if set{property}Attribute() method exists, if it does - use it to assign a value, if it doesn't - use mass assigning.
Something like:
public static function create($attr) {
$indirect = collect($attr)->filter(function($value, $property) {
return method_exists(self::class, 'set' . camel_case($property) . 'Attribute');
});
$entity = parent::create(array_diff_key($attr, $indirect->toArray()));
$indirect->each(function($value, $property) use ($entity) {
$entity->{$property} = $value;
});
$entity->save();
return $entity;
}
I haven't really tested it but it should work. I use something like this in one of my Symfony apps.
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;
}
I would like to add some strings/values to the end of the generated pagination link.
For example, I get this
http://localhost/products/lists/5
I would like to have
http://localhost/products/lists/5/value/anothervalue
So, I need to send those values somehow... :)
Thank u all.
The pagination class has an undocumented configuration option called suffix that you can use. Here's how I use it in one of my apps:
// get the current url segments and remove the ones before the suffix
// http://localhost/products/lists/5/value/anothervalue
$args = $this->uri->segment_array();
unset($args[1], $args[2], $args[3]);
$args = implode('/', $args);
// $args is now 'value/anothervalue'
$base_url = 'http://localhost/products/lists';
$this->pagination->initialize(array(
'base_url' => $base_url,
'suffix' => '/'.$args,
'first_url' => $base_url.'/1/'.$args,
'uri_segment' => 3
));
The application/config/routes.php
$route['products/lists/(:num)/value/(:any)'] = "products/lists/$1/$2";
The controller code application/controllers/products.php
class Products extends CI_Controller {
public function index() {
$this->load->view('welcome_message');
}
public function lists($page = 1, $value = null) {
$this->load->view('product_lists', array('page' => $page, 'value' => $value));
}
}
In this way if your url is like http://localhost/products/lists/5/value/anothervalue
in function lists will be $page = 5 and $value = 'anothervalue' and they will be available in template product_lists ($page, $value)
I'm working on testing a shopping cart, checkout, payment process on Zend Framework with phpunit. I'm testing ShoppingCartController by adding products to cart, a ShoppingCart Model handles product additions by storing product id's in a Zend Session Namespace, and then in another test I want to test that the products were added. The same ShoppingCart Model retrieves a list of added products from the same Zend Session namespace variable.
The add product test looks like this and works well, and the var_dump($_SESSION) was added to debug and shows the products correctly:
public function testCanAddProductsToShoppingCart() {
$testProducts = array(
array(
"product_id" => "1",
"product_quantity" => "5"
),
array(
"product_id" => "1",
"product_quantity" => "3"
),
array(
"product_id" => "2",
"product_quantity" => "1"
)
);
Ecommerce_Model_Shoppingcart::clean();
foreach ($testProducts as $product) {
$this->request->setMethod('POST')
->setPost(array(
'product_id' => $product["product_id"],
'quantity' => $product["product_quantity"]
));
$this->dispatch($this->getRouteUrl("add_to_shopping_cart"));
$this->assertResponseCode('200');
}
$products = Ecommerce_Model_Shoppingcart::getData();
$this->assertTrue($products[2][0]["product"] instanceof Ecommerce_Model_Product);
$this->assertEquals($products[2][0]["quantity"],
"8");
$this->assertTrue($products[2][1]["product"] instanceof Ecommerce_Model_Product);
$this->assertEquals($products[2][1]["quantity"],
"1");
var_dump($_SESSION);
}
The second test attempts to retrieve the products by asking the model to do so, the var_dump($_SESSION) is null already at the beginning of the test. The session variables were reset, I want to find a way to preserve them, can anyone help?
public function testCanDisplayShoppingCartWidget() {
var_dump($_SESSION);
$this->dispatch($this->getRouteUrl("view_shopping_mini_cart"));
$this->assertResponseCode('200');
}
Sorry for pointing you in the wrong direction. Here is a way better way of achieving this, suggested by ashawley from #phpunit channel of irc.freenode.net:
<?php
# running from the cli doesn't set $_SESSION here on phpunit trunk
if ( !isset( $_SESSION ) ) $_SESSION = array( );
class FooTest extends PHPUnit_Framework_TestCase {
protected $backupGlobalsBlacklist = array( '_SESSION' );
public function testOne( ) {
$_SESSION['foo'] = 'bar';
}
public function testTwo( ) {
$this->assertEquals( 'bar', $_SESSION['foo'] );
}
}
?>
== END UPDATE
In function tearDown(): copy $_SESSION to a class attribute and
In function setUp(): copy the class attribute to $_SESSION
For example, this test fails when you remove the functions setUp() and tearDown() methods:
<?php
# Usage: save this to test.php and run phpunit test.php
# running from the cli doesn't set $_SESSION here on phpunit trunk
if ( !isset( $_SESSION ) ) $_SESSION = array( );
class FooTest extends PHPUnit_Framework_TestCase {
public static $shared_session = array( );
public function setUp() {
$_SESSION = FooTest::$shared_session;
}
public function tearDown() {
FooTest::$shared_session = $_SESSION;
}
public function testOne( ) {
$_SESSION['foo'] = 'bar';
}
public function testTwo( ) {
$this->assertEquals( 'bar', $_SESSION['foo'] );
}
}
Also there is a backupGlobals feature but it doesn't work for me. You should try it thought, maybe it works on stable PHPUnit.
that's a very ugly of doing that. The right way should be using dependency injection.
That implies changing your source code to use this class instead of sessions directly:
class Session
{
private $adapter;
public static function init(SessionAdapter $adapter)
{
self::$adapter = $adapter;
}
public static function get($var)
{
return self::$adapter->get($var);
}
public static function set($var, $value)
{
return self::$adapter->set($var, $value);
}
}
interface SessionAdapter
{
public function get($var);
public function set($var, $value);
}
Additional information:
http://community.sitepoint.com/t/phpunit-testing-cookies-and-sessions/36557/2
Using PHPUnit to test cookies and sessions, how?
You can also just create a random session id for your PHPUnit test, and then make sure you pass this session id in a cookie in every further call you make. With Curl, you would use the CURLOPT_COOKIE option and set it to 'PHPSESSID=thesessionidofyourunittest' as such:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=thesessionidofyourunittest');
I explained more in detail and with an example in this stackoverflow answer.