accessing flash messenger not from a controller - php

I'm writing a PHP application using zend framework 2.2.2.
I would like to know how to be able to use the FlashMessanger using zend framework 2.
now I know that it's possible to fetch the Flash Messanger using zf1 using the following code:
$this->messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger');
how it is possible to fetch the flash messenger using zf2 ?
the thing is that I want to the flash messenger to be available in my own utility class
so I don't have the controller available to fetch the messenger from there.
any ideas?
thanks

The FlashMessenger is a ControllerPlugin Zend\Mvc\Controller\Plugin\FlashMessenger and that's where it makes the most sense of using it. Injecting the Messenger into your "UtilityClasses" to me sounds like a somewhat bad idea, since this would make the response-checking so much more complicated and the controllers quite more bloated. So take that in mind.
However it is possible to get the FlashMessenger into any class you want. The only catch is, all the classes you want the FM to be available at, have to be called by the ServiceManager. Your ServiceFactories then would look like this:
// Module#getServiceConfig()
return array('factories' => array(
'MyServiceClass' => function($serviceLocator) {
return new MyService(
$serviceLocator->get('controllerpluginmanager')->get('flashmessenger')
);
}
));
Of course you could re-write it to use setter-injection or even lazy-getters in your ServiceClass if you wish you inject the full ServiceLocator (which isn't advised).

Related

Different behaviour with and without Symfony's response system

I'd like to be able to manage WebDAV directories (and even reimplement the way files are read and written) in Symfony. To do so I found SabreDAV, which is itself a framework with all the basic classes required.
My problem is, while it's quite easy to get a WebDAV server running using SabreDAV alone, it doesn't work that well when I use Symfony.
Without Symfony, it boils down to:
$server = new DAV\Server($rootDirectory);
$server->exec();
And I can use cadaver to access my directory.
More here: http://code.google.com/p/sabredav/wiki/GettingStarted
I tried to do the same in my controller with Symfony, using:
return new Response($server->exec());
but for some reason cadaver doesn't have access to the folder.
I guess I'm missing something about the way responses work in Symfony, but what? SabreDAV uses its own system of http requests and responses, but if (as I presume) Symfony doesn't mess with superglobal variables such as $_SERVER, this shouldn't be an issue.
About requests and responses in Symfony: http://symfony.com/doc/current/book/http_fundamentals.html#requests-and-responses-in-symfony
Here's what I did; it's a bit slow and there must be a better way, but I'll make do with that for the moment:
Controller.php :
$path=(__DIR__.'/../../../../web/public/');
$path=realpath($path);
$publicDir= new \MyClasses\FS\MyDirectory($path);
$server = new \Sabre\DAV\Server($publicDir);
$server->setBaseUri('/Symfony/web/app_dev.php/');
{
$SyRequest = Request::createFromGlobals();
$_server=$SyRequest->server->all();
$_post=$SyRequest->request->all();
}
{
$SaRequest=new \MyClasses\HTTP\Request($_server,$_post);
$resourceStream=false;
$SaRequest->setBody($SyRequest->getContent($resourceStream),$resourceStream);
}
{
$server->httpRequest=$SaRequest;
$SaResponse=new \MyClasses\HTTP\Response();
$server->httpResponse=$SaResponse;
$server->exec();
}
{
$content=ob_get_clean();
}
{
$SyResponse=new Response($content,http_response_code(),headers_list());
}
return $SyResponse;
$server->exec();
Doesn't really return anything. It attempts to set headers itself, and stream the output to php://output (indeed, with the built-in request/response system).
If you want to embed SabreDAV into symfony, the most proper way to solve this is to subclass both Sabre\HTTP\Request and Sabre\HTTP\Response, and set these in the server (setting the ->httpRequest and ->httpResponse properties) before calling ->exec.
Your overridden request/response objects should then map to symfony's equivalents.
I don't know enough about symfony to tell you if they map cleanly and easily though, and I imagine it will in practice be simpler to try to work around symfony's system (although from an architectural standpoint, it will not be the most proper).

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example

Rails style URL mapping in PHP

Is there any standard library to do Rails style URL mapping in PHP? I am not using any framework, all the code is hand-written. Basically, I am looking for a library that does this
example.com/user/1/active
this should map to a user, with id = 1 and status = 2 (those being the parameters). I should be able to define the map.
There are roughly ten thousand ways to do this in PHP.
I've recently become a fan of klein.php, a lightweight bit of router code with some handy convenience methods. It's not a framework, and doesn't get in the way of you using one if you wanted to.
It's basically little more than "here's a URL pattern, and here's the function to run when the pattern matches."
Frameworks are really built to handle that automatically, but short of using a framework, you would be best off writing your own .htaccess rules (if you are using linux or os x), or try checking out how say, CakePHP handles url rewriting and base off of that.
Example:
http://example.com/name/corey
RewriteRule ^(.+)/(.+)$ /$1.php?name=$2 [NC,L]
That would rewrite the above url to /name.php?name=corey
PHP's purpose is not to handle differently formatted URLs. There should be some custom application logic taking care of this.
You've mentioned that you are not using any framework at this moment, so I would like to propose you to include Silex, it's a micro framework based on the components of Symfony 2.
Here's the 'Hello World' example:
require_once __DIR__.'/silex.phar';
$app = new Silex\Application();
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
You've mentioned that you are currently using PHP 5.2. Silex uses namespaces, which are available from PHP 5.3 and so on, so you will have to upgrade your PHP to take this approach.
Go with Symfony framework.
http://symfony.com/blog/new-in-symfony-1-2-toward-a-restful-architecture-part-1
Look at this response:
https://stackoverflow.com/questions/238125/best-framework-for-php-and-creation-of-restful-based-web-services

OO PHP + Ajax without framework

I'm going to write a booking website using php and ajax and I really can't figure how to mix these two tools with a strict object oriented design.
I was used to make a call using ajax to a php web page that returns the right set of values (string, xml, json) in a procedural way.
With object oriented programming how is it supposed to work?
The simplest solution that i can think is to call through ajax a php page that should only instantiate a new object of the right class and then make an echo on the result of a simple call with the data received but this doesn't look very oo...
For example to implement the register function I should make an ajax call to a register.php web page that, in turn, will instantiate a new Registration object r and then simply calls r.register() with the right data.
Is there a better solution to this problem?
I want specify that I can't use any php framework because it's a didactic project and I have this rule that I should respect.
Another specification: I've read a lot of tutorials that describe how to write your own mvc framework but doing this seems to be an overkill for my problem.
Thank you for your help, every idea will be appreciated.
As you already said you don't really need a PHP framework and don't need to build your own MVC implementation
(especially if you are e.g. working with JSON or XML).
Basically you are pretty free on how to do your OO model, so your idea is not necessarily wrong.
Some OO anti patterns I have seen people using in PHP:
Use global variables in classes
Create classes without member
variables resulting in method calls
being the same as in a produral style
Directly accessing $_GET, $_POST etc.
in a class
Echoing html output (imho this should
be done in view templates)
An example for what you might want to do for the registering process processing some $_POST variables
and returning a JSON success message:
<?php
class Registration
{
private $_data;
public function __construct($registrationdata)
{
$this->_data = $registrationdata;
}
public function validate()
{
// ...
}
public function register()
{
// ...
if($this->validate())
return array("registered" => true, "username" => $this->_data["username"],
"message" => "Thank you for registering");
else
return array("registered" => false, "username" => $this->_data["username"],
"message" => "Duplicate username");
}
}
$reg = new Registration($_POST);
echo json_encode($reg->register());
?>
There is no reason to create any classes if all you are doing is calling a couple of unrelated stateless php functions.

Working example Zend_Rest_Controller with Zend_Rest_Client?

I am trying to write a short Rest Service with Zend Framework. But the documentation is not the best at this Part.
I have an ApiController extended Zend_Rest_Controller with all needed abstract methods. My goal is to get Post data and return something.
My client looks like this:
public function indexAction()
{
$url = 'http://localhost/url/public/api';
$client = new Zend_Rest_Client();
$client->setUri($url);
$client->url = 'http://www.google.de';
$result = $client->post();
}
but the provided "$client->url" is not inside the post array on Server side. Does I have to use Zend Rest Server inside the postAction on my ApiController?
If someone has an example how to send and to get the data with Zend Rest, that would be great.
Maybe this tutorial Create RESTful Applications Using The Zend Framework can help.
Have you tried setting it to access 127.0.0.1 rather than localhost? I know this can cause issues sometimes.

Categories