I want to rewrite this code without so many "else's", but still keep it efficient in terms of not checking things or running queries if not needed.
Can someone suggest a better way to write this function?
public static function fetch($content) {
products_library::init();
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
//check the cache
if (file_exists($cache)) {
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if ($mod_date) {
$mod_date = strtotime('date_modified');
if ($cache_date >= $mod_date) { //serve the cache
try {
$soldout = filewriter::read($cache);
$soldout = unserialize($soldout);
} catch (Exception $e) {
$soldout = self::query();
}
}
else
$soldout = self::query();
}
else
$soldout = self::query();
}
else
$soldout = self::query();
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
Thanks
Refactored it into a method that returns instead of else statements
private static function getSoldout() {
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
//check the cache
if (!file_exists($cache)) {
return self::query();
}
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if (!$mod_date) {
return self::query();
}
$mod_date = strtotime('date_modified');
if ($cache_date < $mod_date) {
return self::query();
}
try {
//serve the cache
$soldout = filewriter::read($cache);
$soldout = unserialize($soldout);
return $soldout;
} catch (Exception $e) {
return self::query();
}
}
public static function fetch($content) {
products_library::init();
$soldout = self::getSoldout();
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
I don't understand this line, is there a bug there?
$mod_date = strtotime('date_modified');
Set $soldout to NULL. Then remove the else $soldout = self::query() statement.
After the if statement test $soldout for NULL and it true run the query.
A switch-case block would work wonders here. You'd just have a break statement that would point to a default case. However, if I were in your shoes, I'd attempt to refactor the whole thing, which would take more than a quick fix.
Something like this might work. I'm not sure what's happening inside all the ifs and why you need so many, it might be more compact.
public static function fetch($content) {
products_library::init();
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
$soldout = self::fetchCache($cache);
if ($soldout === false)
{
$soldout = self::query();
}
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
public static function fetchCache($cache) {
if (file_exists($cache)) {
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if ($mod_date) {
$mod_date = strtotime('date_modified');
if ($cache_date >= $mod_date) { //serve the cache
try {
$result = filewriter::read($cache);
$result = unserialize($soldout);
return $result;
} catch (Exception $e) {
return false;
}
}
}
}
return false;
}
Seems to me as if you could default $soldout to be self::query() by setting it to that before the first if check then remove all the elses, so if the conditions doesn't match it will still be self::query(). Might not work depending on what self::query() does.
Related
I got a codeigniter custom_result_object with this:
$user = $this->CI->db->get_where('users', array('email' => $email), 1)->custom_row_object(0,'entities\User');
and everything looks fine. I can update values with my setters.
Before I'm going to save i check my values with:
die(print_r($user));
and the values are correct.
I put my object in my update method.
$this->CI->db->update('users', $user, "id = ".$user->getId());
But the db is not updating. Am I missing something?
Thx!
EDIT:
So by using CI native db-method i can use:
public function save($user)
{
if($user->getId() == NULL){
$this->CI->db->insert('users', $user);
}else{
$this->CI->db->update('users', $user, "id = ".$user->getId());
}
}
Edit 2:
After some more checking I can see that it's not setting variables that are protected. CI is able to get the object through getters and setters but not able to save back to DB?
public function saveData($tbl,$data,$update = false,$previewStr = false){
$set_str = "NO_QUOTES()";
if(isset($data[$set_str])){
foreach($data[$set_str] as $set_key => $set_value){
$this->db->set($set_key, $set_value, FALSE);
}
unset($data[$set_str]);
}
if(isset($update[$set_str])){
foreach($update[$set_str] as $whr_key => $whr_value){
$this->db->where($whr_key." ".$whr_value,NULL,false);
}
unset($update[$set_str]);
if(is_array($update) and count($update) <= 0){
$update = true;
}
}
if($update == false){
$this->db->insert($tbl, $data);
if($previewStr){
return $this->db->last_query();
}else{
return $this->db->insert_id();
}
}else{
$result = NULL;
if(!is_array($update)){
if(is_array($data) and count($data) > 0){
foreach($data as $field => $value){
$this->db->set($field, $value);
}
}
$result = $this->db->update($tbl);
}else{
$result = $this->db->update($tbl, $data,$update);
}
if($previewStr){
return $this->db->last_query();
}else{
return $result;
}
}
}
public function delData($tbl = false,$where = array()){
if($tbl !== false){
return $this->db->delete($tbl, $where);
}else{
return false;
}
}
public function simpleQuery($query,$return_array = false,$return_single = false)
{
$ac = $this->db->query($query);
if($return_array === false){
return $ac;
}else{
if($return_single === false){
return $ac->result_array();
}else{
return $ac->row_array();
}
}
}
Use above code in your model and you i am giving you how to update it use below code in your controller you can insert update and delete by above code
$result=$this->Products_model->saveData("customer",array("customer_name"=>$name),array("cust_id"));
I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.
I am trying to search a value from database table and display result to web site using laravel. my controller.php code is here
else
{
try
{
$pname = Input::get('pname');
$parents = ForumParent::where('pname', $pname)->first();
if(empty($parents))
{
throw new \Exception("Parent not found");}
return Redirect::route('view',$parents->paddress);
}
catch (Exception $e)
{ return "not value";
//abort(404);
}
}
}
public function view($paddress)
{
$parents=ForumParent::find($paddress);
$users=User::all();
return View::make('search.viewsearch')
->with('parents',$parents)
->with('users',$users);
}
Change this:
$parents = ForumParent::where('pname', $pname)->first();
to this:
$parents = ForumParent::where('pname', '=', $pname)->first();
OR
$parents = ForumParent::where('pname','LIKE', '%' . $pname . '%')->first();
See, if that helps.
I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players