How can use variable model several time, something like this code:
$Db = Model::where(['user_id'=>1]);
$Db->first();
$Db->get();
$Db->delete();
I dont want using repeat $Db for get,first,delete or etc
for example I dont prefer using bad code something like this:
$Db = Model::where(['user_id'=>1])->first();
$Db = Model::where(['user_id'=>1])->get();
$Db = Model::where(['user_id'=>1])->delete();
or ...
I want separate class object for any first() or get() or ...
I haven't tested this but try using query builder https://laravel.com/docs/5.4/queries#introduction
$qb = DB::table('users')->where('votes', '>', 100);
$qb->get();
$qb->first();
$qb->delete();
Another option is to use a closure
$model = function() {
return Model::where(['user_id'=>1]);
};
$model()->get();
$model()->first();
$model()->delete();
Again, not tested :)
You can use:
$Db = Model::where(['user_id'=>1]);
with(clone($Db))->first();
with(clone($Db))->get();
with(clone($Db))->delete();
The best way you can do is to create a helper or class.
// create
public static function user_info($user_id) {
return Model::where(['user_id' => $user_id]);
}
// call
Helpers:user_info(1)->first();
Helpers:user_info(1)->get();
Helpers:user_info(1)->delete();
Related
Im new to zendframework & zend db..any help will be great!!
(Normal Way)
Lets say i want to get data..so im using this
Inside Controller
$db = new Studentfinance_Model_DbTable_FeeItem();
$data =$this->db->getDate();
Inside Model
protected $_name = 'tbl_foo_foo';
protected $_primary = "foo_id";
public function getData() {
$db = Zend_Db_Table::getDefaultAdapter();
$selectData = $db->select()
->from(array('a'=>$this->_name))
->joinLeft(array('c'=>'tbl_bar'), 'c.idBar = a.id',array('DefinitionDesc','Status'))
->group('a.id')
$fc_cat = $db->fetchAll($selectData);
return($fc_cat);
}
For Above line of code...i understand the way its work..
But for below..i have a bit problem to understand..same concept..the purpose to get the data
inside controller/form
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->fetchAll();
i try to find function fetchAll()...but i dont find it inside Model FeeCategory...can someone explainn this
$feeCategoryDb->getData() already sets up the query and runs "fetchAll" and returns the results. So all you need to do is:
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->getData();
Is it possible get the value of a route placeholder within a Slim container? I know I can access the placeholder by adding a third parameter to the request but I'd like to have it injected so I'm not assigning it on each request.
I've tried $app->getContainer('router') but I can't seem to find a method to actually pull the placeholder value.
Example:
$app = new Slim\App;
$c = $app->getContainer();
$c['Controller'] = function() {
$userId = // how do I get the route placeholder userId?
return new Controller($userId);
};
$app->get('/user/{userId}','Controller:getUserId');
class Controller {
public function __construct($userId) {
$this->userId = $userId;
}
public function getUserId($request,$response) {
return $response->withJson($this->userId);
}
}
Without some 'hacky' things this will not work because we have no access on the request object build by slim, while the controller get constructed. So I recommend you to just use the 3rd parameter and get your userid from there.
The 'hacky' thing would be todo the same, what slim does when you execute $app->run(), but if you really want todo this, here you'll go:
$c['Controller'] = function($c) {
$routeInfo = $c['router']->dispatch($c['request']);
$args = $routeInfo[2];
$userId = $args['userId'];
return new Controller($userId);
};
Note: slim3 also urldecoded this values so may do this as well urldecode($args['userId']) Source
create a container wrapper and a maincontroller then extend all your controller from your maincontroller, then you have access to the container.
here is how i solved this problem:
https://gist.github.com/boscho87/d5834ac1ba42aa3da02e905aa346ee30
Im trying to figure out how to call functions based on what a user clicks on a form. But im not sure if im doing it right.
I have a number of classes, lets say 3 for different ways to connect to a site, the user clicks on which one they would like.
FTP
SFTP
SSH
Which i have named 'service' in my code.
I don't want to run a whole bunch of IF statements, i would rather try and build the call dynamically.
What i have at the moment is as follows
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
$service->testConn($request);
Im getting the following error
Call to a member function testConn() on string
Im not sure im doing this right.
Any help would be greatly appreciated.
Thanks
First of all $service is a string on which You cannot call method, because it is not an object (class instance).
I think it is a great example of where You can use Strategy Pattern which look like that:
class BackupStrategy {
private $strategy = null;
public function __construct($service_name)
{
switch ($service_name) {
case "ftp":
$this->strategy = new FTPBackup();
break;
case "sftp":
$this->strategy = new SFTPBackup();
break;
case "ssh":
$this->strategy = new SSHBackup();
break;
}
}
public function testConn()
{
return $this->strategy->testConn();
}
}
And then in place where You want to call it You call it by:
$service = new BackupStrategy($request->input('service'));
$service->testConn($request);
I suggest You to read about Design Patterns in OOP - it will help You a lot in the future.
How about this:
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
${$service}->testConn($request);
This is called "Variables variable": http://php.net/manual/en/language.variables.variable.php
// Create class name
$className = $request->get('service') . '_backup';
// Create class instance
$service = new $className();
// Use it as you want
$service->testConn($request);
So I basically want to do this:
$this->container['Menu_builder'] = $this->container->factory(function ($c) {
return new Menu_builder($parameter_1, $parameter_2);
});
Where $parameter_1 and $parameter_2 are passed in from the call, like this:
$menu_builder = $this->container['Menu_builder']('account', 'reset_password');
I know the above syntax is incorrect, but I want to pass these strings into the call to $this->container->factory.
Is this possible?
For example, if I wanted to instantiate the Menu_builder from various controller functions with different parameters for each controller function.
FWIW, you can also include an anonymous function within your container.
$this->container['Menu_builder'] = function() {
// do stuff here
return function($parameter_1, $parameter_2) {
return new Menu_builder($parameter_1, $parameter_2);
};
};
Use this way:
$localfunc = $this->container['Menu_builder'];
$result = $localfunc($parameter_1, $parameter_2);
Notice that in this case I'm not using a factory. That's because you can execute the anonymous function with different values each time.
You just can use use() to pass your variables to the anonymous functions, e.g.
//your parameters needs to be defined here:
$parameter_1 = "XY";
$parameter_2 = 42;
$this->container['Menu_builder'] = $this->container->factory(function ($c)use($parameter_1, $parameter_2) {
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See here
return new Menu_builder($parameter_1, $parameter_2);
});
Im wondering if there is a way to autocreate object if a property is called. An example:
<?php
echo $myObj->myProperty
?>
This code will of course fail because i did not initiate $myObj before reading the property.
What im looking for is a way to automaticly initiate $myObj based on "myObj".
Something like:
<?php
class myObj {
public myProperty = 'BlaBla';
}
echo $myObj->myProperty; //outputs BlaBla instead of failing
?>
I know about __autoload($classname) but that only works of initiating classcode with i.e. an include(), so that is not what im after.
You can use magic methods to automate stuff like that...
http://www.php.net/manual/en/language.oop5.magic.php
Just to close this question, this is what i ended up doing:
preg_match_all("/\\\$(.*?)->/si", $code, $matches);
I loop trough the code i get from database looking for any references to objects like
$xxxx->
Then i loop trough the references and create the objects
foreach($matches[1] as $key=>$value) {
$$value = Connector::loadConnector($value);
}
Where the "loadConnector is:
public function loadConnector($connector, $params = NULL) {
require_once $connector. ".php";
$c_name = $connector;
return new $c_name($params);
}
This is of course based on my file structure and it also needs some errorhandling, but so far it looks like it solves my problem :)
BR/Sune