PHP 5.3.2 alternative to using $this inside an anonymous function? - php

I am using Laravel 4 and PHP to build a new application. It works fine on my dev server running PHP 5.4.x however my boss insist that it has to run version 5.3.2
I have spent the whole day fixing everything to work with 5.3.2 and almost have everything, so I thought, until I ran into an issue with the code below.
My problems start at this line...
DB::transaction(function($clock_in_webcam_image) use ($clock_in_webcam_image)
I believe this type of code might not work with this version of PHP? If that is the case, what are my options to run this same code or have it doing the same action?
Would appreciate any help with this. Very unfortunate that my boss told me straight out that no he will not allow us to update to a newer PHP so I am stuck in a hard spot right now
// Create a new time card record when a User Clocks In
public function createTimeCard($clock_in_webcam_image) {
// Create both Timecard and timecard record tables in a Transaction
DB::transaction(
function ($clock_in_webcam_image) use ($clock_in_webcam_image) {
$timeCard = DB::table('timeclock_timecard')->insertGetId(
array(
'user_id' => $this->user->user_id,
'clock_in_datetime' => $this->dateTime->format($this->dateFormat),
'clock_in_timestamp' => $this->dateTime->getTimestamp(),
'clock_in_webcam_image' => $clock_in_webcam_image
)
);
$timeCardPunchEntry = DB::table('timeclock_punch_entry')
->insertGetId(
array(
'timecard_id' => $timeCard,
'user_id' => $this->user->user_id,
'created_at_datetime' => $this->dateTime->format($this->dateFormat),
'created_at_timestamp' => $this->dateTime->getTimestamp(),
'clock_type' => 'clock_in',
'webcam_image' => $clock_in_webcam_image
)
);
return $timeCard;
}
);
}
UPDATE
In response to bansi's comment...is this what you mean to do...
DB::transaction(function() use($myModel){
$myModel->updateTable1();
$myModel->updateTable2();
})

Before PHP 5.4.0, you could not use $this inside an anonymous function. There is a simple workaround though where you can use the use construct to pass variables into the functions scope. Also, you are using the use construct incorrectly as $clock_in_webcam_image is not defined in the parent scope.
$user = $this->user;
$dateTime = $this->dateTime;
DB::transaction(function($clock_in_webcam_image) use ($user, $dateTime) {
// snip
array(
'user_id' => $user->user_id,
'clock_in_datetime' => $dateTime->format($this->dateFormat),
'clock_in_timestamp' => $dateTime->getTimestamp(),
'clock_in_webcam_image' => $clock_in_webcam_image
)
// snip
});

try this. please check you don't have another insertTimecard defined.
// Create a new time card record when a User Clocks In
public function createTimeCard($clock_in_webcam_image)
{
// Create both Timecard and timecard record tables in a Transaction
DB::transaction($this->insertTimecard($clock_in_webcam_image));
}
private function insertTimecard($clock_in_webcam_image)
{
$timeCard = DB::table('timeclock_timecard')->insertGetId(
array(
'user_id' => $this->user->user_id,
'clock_in_datetime' => $this->dateTime->format($this->dateFormat),
'clock_in_timestamp' => $this->dateTime->getTimestamp(),
'clock_in_webcam_image' => $clock_in_webcam_image
)
);
$timeCardPunchEntry = DB::table('timeclock_punch_entry')->insertGetId(
array(
'timecard_id' => $timeCard,
'user_id' => $this->user->user_id,
'created_at_datetime' => $this->dateTime->format($this->dateFormat),
'created_at_timestamp' => $this->dateTime->getTimestamp(),
'clock_type' => 'clock_in',
'webcam_image' => $clock_in_webcam_image
)
);
return $timeCard;
}

Related

PHP create object from class with public arrays

I have a class for configuration on my script and I implement the config. I then want to use the options as an object reference like the following, but not sure how to get it all the way to the final object field and also how to make it recognize sub arrays too
class Configuration {
public $cookies = array(
"cookie_prefix" => "site_",
"site_settings" => array(
"domain" => "somesite.com",
"https_only" => TRUE
),
"another_item" => "and some data too"
);
}
$config = new Configuration();
echo $config->cookies->cookie_prefix;
echo $config->cookies->site_settings->domain;
Right now it works if I do the following
echo $config->cookies['cookie_prefix'];
echo $config->cookies['site_settings']['domain'];
But I want it to be an object all the way down. Can't wrap my brain around this one for some reason?
I know this is easily done - I am just missing the way how...
I just passed the items in the __construct as json and its working the way I wanted now, duh.
public $cookies = array(
"cookie_prefix" => "site_",
"site_settings" => array(
"domain" => "somesite.com",
"https_only" => TRUE
),
"another_item" => "and some data too"
);
public function __construct() {
$this->cookies = json_decode(json_encode($this->cookies));
}

Laravel 5 passing page info with array

I'm trying to pass data about the page state (navbar links having active class when you are in that exact page), page title. I do so with an indexed array $pageInfo, however I am getting a syntax error and doen't know where?
Also do you think this is a good method or should I use view->share() instead?
public function clases()
{
$pageInfo[] =
(
'page_title' => 'Clases',
'menu_active' => 'CLases',
'sub_menu_active' => '',
);
return view('clases.list', compact('pageInfo'));
}
public function domicilio()
{
$pageInfo[] =
(
'page_title' => 'Clases a domicilio',
'menu_active' => 'Clases',
'sub_menu_active' => 'Clases a domicilio',
);
return view('clases.domicilio', compact('pageInfo'));
I suggest you read PHP basic syntax.
Basically you want to do this:
$pageInfo =
[
'page_title' => 'Clases',
'menu_active' => 'CLases',
'sub_menu_active' => '',
];
Arrays have a syntax of [key => val, ...] in PHP, you're using () as it seems.
Also $someArray[] = someValue, will append the someValue to an existing array, in your case that would create another, unwanted level of your array.
And last, you're not ending the domicilio() function. But I'll assume you just didn't paste it in (you should add } at the end, if that's not the case).

Symfony convert entity to json format by looping foreach

I have a little REST API in my project. And ofcourse i use json as my return data to work with.
I am using symfony in the backend and angularJs in the frontend. At the moment i convert my entity to json by looping true my result and filling an data array to return as json.
EXAMPLE:
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$warehouseId = $this->get('session')->get('warehouse');
$warehouse = $em->getRepository('BubbleMainBundle:Warehouse')->find($warehouseId);
$trip = $em->getRepository('BubbleMainBundle:Trip')->find($id);
$data = array(
'id' => $trip->getId(),
'driver' => $trip->getDriver(),
'status' => $trip->getStatus(),
'date' => $trip->getPlanningDate()->format('Y-m-d')
);
if ( count($trip->getStops()) > 0 ) {
foreach($trip->getStops() as $stop)
{
$data['assignedStops'][] = array(
'id' => $stop->getId(),
'status' => $stop->getStatus(),
'date' => $stop->getDeliveryDate()->format('Y-m-d'),
'sort' => $stop->getSort(),
'company' => array(
'name' => $stop->getToCompany()->getName(),
'lat' => $stop->getToCompany()->getLat(),
'lng' => $stop->getToCompany()->getLng(),
'address' => $stop->getToCompany()->getAddress(),
'zip' => $stop->getToCompany()->getZip()
),
);
}
} else {
$data['assignedStops'][] = '';
}
$response = new jsonResponse();
$response->setData($data);
return $response;
}
This works. But sometimes i have have (google chrome timeline) waiting responses of 6 seconds for just a simple query and json response.
Is looping true the entity to much? Or do i need another approach for converting my entities to json format?
thx anthony,
If you are using PHP 5.4 or above then considering using the JsonSerializable interface with your entities:
http://www.php.net/manual/en/class.jsonserializable.php
This will allow you to control how your entities are converted to JSON which will allow you to call json_encode directly on your entities without having to loop through and convert them to arrays.
As for the performance issue you'd need to profile your script to find out where the performance bottleneck is. From looking at your code one potential issue that you might want to look into is to make sure you are fetching all the data in your original query (i.e stops and companies) and you are not executing additional queries in the foreach loop to fetch the missing stop and company data.
I recommend you (since you are using Symfony2 as a backend and you need an API) to definitely try out this bundle... It's easy to use and to setup and as an extra you can also generate a nice documentation for it.
It will speed up your development and code.

How to create an empty field if the field doesn't exist in MongoDB

I have a document that is created on weakly bases (field delimeter hold date) for each user's week.
Every time the user session expires I check to see the user has a document for that particular week (so that all updates dont fail)
I am trying to avoid 2 fetches : 1) a fetch to check if the document exists, 2) create another query that creates or not that document depending on whether it exists already
I was wondering if there is such a function within mongo... Create if doesn't exist otherwise do nothing?
Currently, upsert inserts if it is not there or updates if it is there. Thus, is not a valid solution. I need if ( !exist){ update/insert ) else { do nothing }
public function createUserSocialWallForUser( MongoId $userMongoID, $delimeter ) {
$db = $this->db()->socialWall;
$where = array( 'userId' => $userMongoID,
'delimeter' => $delimeter
);
$data = array( 'userId' => $userMongoID, 'delimeter' => $delimeter, 'event' => array() );
$option = array ('upsert' => true);
$db->update( $where, $data, $option);
}
Sound like a perfect fit for $setOnInsert:
$data = array(
'$setOnInsert' => array(
'userId' => $userMongoID,
'delimeter' => $delimeter,
'event' => array()
)
);
This way the update only sets the values if the upsert needs to do an insert (the not-exists case).
Note that this requires at least v2.4 of MongoDB.

phpunit data provider

I am working on PHPunit tests and so far everything is great. There is one issue, however, and it is with the following setup. Ideally I'd like to select the next value in the sequence (postgreSQL) and pass that into the function so I can validate it against the array returned from my class being tested (new row in database).
The issue is that before the array is returned from the data provider (if I echo it) it is the correct value, but during the test it comes through as blank. Is there a particular series of steps I'm missing in here in terms of what I expect or must I do this a different way?
/**
* #dataProvider testSignupProvider
*/
public function testSignup($a, $b, $c)
{
...stuff is done with $a,$b,$c
}
public function testSignupProvider()
{
$uid = fetchOne(X("SELECT currval('users_id_seq')"));
return array(
array(false, array(), $error4),
array(
'email'=>'stack#overflow.com',
'password'=>'youaintgonnagetit',
$error3
),
array(
array('id'=>$uid,'email'=>'PHPUNIT#gmail.com','username'=>'Guest'),
array('email'=>'PHPUNIT#gmail.com','password'=>'youaintgonnagetit'),
null
)
);
}
Output:
Array
(
- [id] =>
+ [id] => 2
[email] => PHPUNIT#gmail.com
[username] => Guest
)
I've gotten around this by assigning the 'id' array element to '#id' and in the function test I pull the current id in the sequence at that time.
Still will accept an answer to anyone who can tell me why this behavior occurs but hopefully this will help anyone else with this issue.

Categories