How to custom title tag and meta tag description in ZF3? - zend-framework3

I'm using Zend Framework description and I'm trying to customize title tag like ZF2 documetation recommends, but I've got this error:
Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException:
Unable to resolve service "viewHelperManager" to a factory; are you
certain you provided it during configuration? in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:681
Stack trace: #0
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(757):
Zend\ServiceManager\ServiceManager->getFactory('viewHelperManag...')
1 /var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(200):
Zend\ServiceManager\ServiceManager->doCreate('viewHelperManag...') #2
/var/www/html/basketmetrics/module/Stats/src/Module.php(43):
Zend\ServiceManager\ServiceManager->get('viewHelperManag...') #3
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(322):
Stats\Module->setLayoutTitle(Object(Zend\Mvc\MvcEvent)) #4
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(171):
Zend\EventManager\E in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php
on line 681
This is my code on Module.php
namespace Stats;
class Module
{
const VERSION = '3.0.2';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function onBootstrap($e)
{
// Register a render event
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function setLayoutTitle($e)
{
$matches = $e->getRouteMatch();
$action = $matches->getParam('action');
$controller = $matches->getParam('controller');
$module = __NAMESPACE__;
$siteName = 'BasketMetrics';
// Getting the view helper manager from the application service manager
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
// Getting the headTitle helper from the view helper manager
$headTitleHelper = $viewHelperManager->get('headTitle');
// Setting a separator string for segments
$headTitleHelper->setSeparator(' - ');
// Setting the action, controller, module and site name as title segments
$headTitleHelper->append($action);
$headTitleHelper->append($controller);
$headTitleHelper->append($module);
$headTitleHelper->append($siteName);
}
}
I don't know If I'm doing something wrong, or if I cannot do it like in ZF2.
And meta tag "description" how can I customize it?

->get('ViewHelperManager')
Up case

Related

Accessing & Outputting $ElementalArea in Silverstripe 4

In a Silverstripe 4 project we have the following method under PageController.php for outputting the content of a page as JSON:
class PageController extends ContentController
{
private static $allowed_actions = array(
'json'
);
public function json(HTTPRequest $request)
{
$data = array();
$data['ID'] = $this->ID;
$data['Title'] = $this->Title;
$data['Breadcrumbs'] = $this->obj('Breadcrumbs')->forTemplate();
$data['Content'] = $this->obj('Content')->forTemplate();
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}
}
Now I would like to do the same thing with a page running the Elemental module. Elementals allows page content to generated by a number of dynamic/ configurable blocks.
To access elemental I use the following template code: $ElementalArea - which returns generated HTML.
I need to replace the following line with one that returns the HTML generated by $ElementalArea:
$data['Content'] = $this->obj('Content')->forTemplate();
I'm not sure of the correct way to do this, any suggestions are appreciated.
Exactly the same way - $this->ElementalArea()->forTemplate().

Slim log writer with sqlite

I have configured slim to write logs to log files as the standard way. But this is not effective when we want to search large and all the logs at a given time. So I want to write those logs to a separate sqlite DB.
My question is how can I set the log writer to write the messages (as done in the Zend framework) ?
P S: I know that I can create a PDO object and use the queries. But I don't want to change the existing code. Just prefer to set the writer and let the framework do the job for me.
I managed to do this as follows,
Create the sqlite connection
$sqlite = new PDO('sqlite:./logs/log.db');
Create my own LogWritter similar to the framework
<?php
/**
* Description of LogWritter
*
* #author Ruwantha.Lankathilaka
*/
class LogWritter {
protected $sqliteConnection;
public function __construct($connection) {
$this->sqliteConnection = $connection;
}
/**
* Write function will bypass the slim default LogWriter and will return
* last inserted log id which could be used as a reference
*
* #param type $object will get the error message
* #param type $level will get the error levels of \Slim\Log
* #return mix if successfully logged will return the last insert id, else
* will return false
*/
public function write($object,$level) {
//Determine label
$label = 'DEBUG';
$message = (string) $object;
switch ($level) {
case \Slim\Log::FATAL:
$label = 'FATAL';
break;
case \Slim\Log::ERROR:
$label = 'ERROR';
break;
case \Slim\Log::WARN:
$label = 'WARN';
break;
case \Slim\Log::INFO:
$label = 'INFO';
break;
}
$sqliteQuery = "INSERT INTO logs (lable,message) VALUES (:lable,:message)";
$statement = $this->sqliteConnection->prepare($sqliteQuery);
$result = $statement->execute(array(':lable'=>$label,':message'=>$message));
if(!empty($result)){
return $this->sqliteConnection->lastInsertId();
}else{
return false;
}
}
}
Add the LogWritter to the index
Add the LogWritter to the Slim app
$app = new \Slim\Slim(array(
'log.writer' => $logWriter,
'log.enabled' => true,
'log.level' => \Slim\Log::DEBUG,
'debug' => true
));
now you can get the log from app
$retult = $app->log->error('test error');
$result will have the inserted log id false if the log failed
Hope this will help someone in future.

Drupal Object of class stdClass could not be converted to int

Hi I have the following drupal module
/**
* Implementation of hook_menu_alter().
*
* #param array $items
* Menu items keyed by path.
*/
function ajax_privacy_menu_alter(&$items) {
$items['node/%']['access callback'] = 'check_access';
$items['node/%']['access arguments'] = array(1);
}
function check_access($node_id)
{
if($node_id!=29)
return TRUE;
else
return FALSE;
}
If i type node/29 it returns access denied message as expected
but for other nodes ( eg: node/24 ) I get the following error
Notice: Object of class stdClass could not be converted to int in
check_access() (line 19 of
/home/pagergbr/public_html/pagerail/sites/all/modules/ajax_privacy/ajax_privacy.module).
and all the nodes in my site show up along with node/24. Please help
Your access callback gets $node object as an argument, try this:
function check_access($node) {
if ($node->nid != 29) {
...
}
}

Symfony PunkAveFileUploaderBundle > imagename before handleFileUpload

The Symfony2 PunkAve FileUpload Bundle works, but because of the returns inside the UploadHandler of BlueImp, it is not possible to get the filename.
<?php
/**
*
* #Route("/upload")
* #Template()
*/
public function uploadAction(Request $request)
{
$editId = $this->getRequest()->get('editId');
if (!preg_match('/^\d+$/', $editId))
{
throw new Exception("Bad edit id");
}
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('Foobar:Foobar')->find($editId);
$destinationFolder = 'test';
$fileUploader = $this->get('punk_ave.file_uploader');
$imageName = $fileUploader->handleFileUpload(array('folder' => $destinationFolder ));
$imageEntity = new \Foobar\Entity\Image();
$imageEntity->setImage($imageName);
$imageEntity->setFolder($destinationFolder);
$em->persist($media);
$em->flush();
return true;
}
The example above uploads the image.
The variable $imageName triggers the fileUploadHandler. There is somewhere a return, why it doesn't go the the next lines where it should save the imagename.
How can I still get it working in Symfony? To save the filename in the Entity after he handled the upload?
As they said in documentation: handleFileUpload DOES NOT RETURN as the response is generated in native PHP by BlueImp's UploadHandler class. handleFileUpload has exit(0); at the end so when you call it then entire process stops there. If you want to save files to database you should do it in action which handles request (from documentation's example it will be editAction) and there, again as documentation said, use getFiles to get the list of filenames and mirror that in your database as you see fit.

Help me write a PHPUnit Test for the following method

public function getAvailableVideosByRfid($rfid, $count=200) {
$query="SELECT id FROM sometable WHERE rfid='$rfid'";
$result = mysql_query($query);
$count2 = mysql_num_rows($result);
if ($count2){ //this rfid has been claimed
return 0;
}
My assertions are :
1). $rfid is a string 5 characters long
2). I am getting a valid result set
Thank You
Please assume that I have the following Unit Test code:
class videoSharingTest extends PHPUnit_Framework_TestCase {
/**
* #var videoSharing
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() {
$this->object = new videoSharing;
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
}
public function testGetAllVideosByRfid() {
******What should I put here*****
}
You need to decentralize your database, typically with a Database abstraction layer which you would mock out. Thus adding a ->setDatabase(), etc. on the object that has the method you are using. Then inside your setUp() { ... } you would set the Database object to a mock:
$this->object->setDatabase($mockDb);
Then you would change
$result = mysql_query($query);
$count2 = mysql_num_rows($result);
to use some form of PDO - so that you could call setDatabase() with a PDO Sql Lite. For example:
setUp() { $this->object->setDatabase($mockDb); }
testFunction() {
$rfid = 'the rfid to use in the test';
//make sure no videos exist yet
$this->assertEquals(0, count($this->object->getAvailableVideosByRfid($rfid, ..);
//you may want to assert that it returns a null/false/empty array/etc.
$db = $this->object->getDatabase();
$records = array(... some data ...);
$db->insert($records); //psuedo code
$vids = $this->object->getAvailableVideosByRfid($rfid, ..); //however you map
$this->assertEquals(count($records), count(vids));
foreach($vids as $video) {
//here you would map the $video to the corresponidng $record to make sure all
vital data was stored and retrieved from the method.
}
}
Typically this would all be done in PDO Sqlite so that no true database would be made/created just for the unit test & that it would live and die with the test, and any developer anywhere could use it with no configuration needed.

Resources