I have a problem with this code in Silex. I am programming a tiny webcart and i dont understand how session object works in Silex. This is my code and it always die with:
Fatal error: Function name must be a string session
In this lines:
$amount = $app['calculate_amount']($app['session']->get('cart'));
$items = $app['calculate_items']($app['session']->get('cart'));
Any ideas?
Thanks!
Cheers!
$app['calculate_amount'] = function ($cart) use ($app) {
$amount = 0.00;
$sql = "SELECT * FROM products WHERE id = ?";
if(is_array($cart))
{
foreach($cart as $id => $qty)
{
$product = $app['db']->fetchAssoc($sql, array($id));
$amount += $product["price"]*$qty;
}
}
return $amount;
};
$app['calculate_items'] = function ($cart) {
$items = 0;
if(is_array($cart))
{
foreach($cart as $id => $qty)
{
$items += $qty;
}
}
return $items;
};
$app->before(function (Request $request) use ($app) {
if ($request->get('save') != NULL)
{
foreach ($app['session']->get('cart') as $id_isbn => $qty)
{
if ($request->get('$id_isbn')=='0')
{
$app['session']->set('cart', array('$id_isbn' => NULL));
}
else
{
$app['session']->set('cart', array('$id_isbn' => $request->get('$id_isbn')));
}
}
$amount = $app['calculate_amount']($app['session']->get('cart'));
$items = $app['calculate_items']($app['session']->get('cart'));
$app['session']->set('amount', $amount);
$app['session']->set('items', $items);
}
});
Quoting from the docs of Pimple, the DIC behind silex:
Direct link.
So in short: pimple saw your anonymous functions as service definitions and ran them the first time you accessed them. You’ll need to
protect()them if you want to store the functions themselves for later retrieval.