PHP - delegating tasks to executables - php

In the application I've written there is a whole class that only takes in some parameters, eventually fetches the db for other parameters, and then returns the results to the asking class. It only handles data, so it would be perfect to "outsurce" those functions to something more efficient than PHP.
I've read the official php faq page on "PHP and COM", and seen that it is not possible to run a precompiled dll from php.
So, do you think it is possible and worth to do it with some other methods? And how would you do it?
Maybe PHP/Java Bridge / RESTful WS could do, but still java does not sound like the best option (according to this post it's "clunky")
HipHop would be a great solution, but as of now it's way too early to use it in production for my needs.
All the solutions listed here seem to be aimed at creating an .exe file for making a standalone win app, whereas my app is hosted on a centOS server and I haven o need to port it to windows (or at least that's not my intention right now).

I use C++ and RabbitMQ to tie it together. I've also had success, when there wasn't much of a scope for the project, at using Redis as a tie in.
Can't say enough good things about using a message bus to separate processes (like RabbitMQ).
If you're just getting started with RabbitMQ, I'd highly recommend RabbitMQ in Action.
You don't have to use C++ though. That's one of the major benefits of using message buses; you can substitute later, if need be (and the API stays the same). Here are a list of clients that can receive and post messages to RabbitMQ: http://www.rabbitmq.com/devtools.html
Insert favorite, high-performance language here.

Related

Websockets & PHP

I'm starting to consider websockets as a solution to replace long polling in a new build PHP app I am commissioning.
I have a few questions which I wonder if people could help me out with.
Can a Nodejs server call PHP and if it did wouldn't it suffer the same shortcomings as just going through Apache in terms of the connections? We all know nodejs is non blocking and Apache etc isn't but if Nodejs is just making a call to a PHP server in it's own procedure would that not bottle neck in a similar way?
Are PHP and websockets a good match?
Are there any good js libraries besides socketio which apparently only works with Nodejs?
Has anyone found a good tutorial which uses websockets and a PHP backend maybe using something like that Ratchet PHP library which might help me get on my way?
Thoughts would be muchly appreciated.
Please excuse my paraphrasing of your questions.
1: Can Node.js call PHP, and wouldn't that have the same shortcomings as Apache?
Calling a run-once PHP script will have the same general shortcomings as calling a web page, except that you are removing an extra layer of processing. Apache or any web server itself is such a thin layer that, while you'll save some time, the savings will be insignificant.
If PHP is more effective at gathering data for your clients than Node.js, for whatever reason, then it might be wise to include PHP in your application.
2: Are PHP and WebSockets a good match?
Traditional PHP scripts are normally intended to be run once per request. The vast majority of PHP developers are unfamiliar with event driven development, and PHP itself does not (yet) have support for asynchronous processing.
PHP is a fast, mature scripting language that is only getting faster, even with all of its many warts and shortcomings. (Some say that its weak typing is a shortcoming. Others say that it's a shortcoming that its typing isn't weak enough.)
That said, the minimum that any language needs in order to implement WebSockets is the ability to open up a basic TCP port and listen for requests. For PHP, it is implemented as a thin wrapper around the C sockets library, and there are additional extensions and frameworks available that can also change the feel of working in TCP sockets with PHP.
PHP's garbage collector has also matured. Memory leaks come either from gross disregard for the memory space (I'm looking at you, Zend Framework) or from intentional sabotage of the garbage collection system by developers who think they're clever or want to prove how easy it is to defeat the GC. (Spoiler: It's easy in every language, if you know the details!)
It is quite possible and very easy to set up a daemon (long running background process) in PHP. It's even possible to make it well behaved enough to gracefully restart and hand its connections off to a new version of the same script, or even the same script on the same server running different versions of PHP, though this is treading out of scope just a tiny little bit.
As for whether it's a good match, that is completely up to the developer. Are you willing, able, and happy to work with PHP to write a WebSockets server, or to use one of the existing servers? Yes? Then you're a good match for PHP and WebSockets.
3: JS Libraries for WebSockets
I honestly haven't researched them.
4: Tutorials for using PHP and Websockets
I'm personally fond of this tutorial: http://www.phpbuilder.com/articles/application-architecture/optimization/creating-real-time-applications-with-php-and-websockets.html
Although I have it on good authority that the specifics of that tutorial will soon be obsolete for that specific WebSockets server. (There will still be an actively maintained legacy branch for that server, though.)
In case of link rot:
Using the PHP-Websockets server (available on Github, will be homed soon), extend the base WebSocketServer abstract class and implement the abstract methods process(), connected(), and closed().
There's much better information at the link above, though, so follow it as long as the link exists.
It would hit the same bottleneck if you go through apache. This can be remedied by using a different web server, such as lighthttpd or nginx. You won't even need node at all.
PHP does not have decent shared memory making the biggest advantages of a WebSockets irrelevent. It should be decent enough if you don't want interaction between users, but even then I would have to frown upon the usage of PHP. PHP is great for a lot of things, but real-time communication is not one of them.
You might want to look at https://github.com/einaros/ws.
PHP is not a good back-end. Anything with an execution model that isn't run-and-forget in its own sandbox, such as Node, .NET, C/C++ and Java are good matches. PHP is suited for short running executions, such as actual web sites and even web services -- but not real time connections.

How is the Twelve-Factor App manifesto applied to PHP projects?

I just read the Twelve-Factor App, which looks like a pretty comprehensive set of rules to apply in a web-based application. It uses python or rails in its examples, but never php... I was wondering which factors of the manifesto can be applied to PHP projects and how?
Thanks
Short answer:
All points apply to PHP as the twelve factor app manifesto refers specifically for web apps.
PHP has a very hard time complying to twelve factor, in particular in the items 2, 7, 8 9 (as a side effect of 7 and 8) and 12 (partially). Actually that's the first really grounded argument I have heard in the whole "PHP sucks" rant that is common on the Ruby and Python communities (don't get me wrong, I think Ruby and Python are better languages, but I don't hate PHP, and definitively hate the "my language is better" rants.)
Being that said, it may be that your PHP project is not a web app or SaaS, but just a simple website, so you may just deem that twelve factor is not a need.
Long answer: A point-by-point analysis would be:
Codebase: not an issue
Dependencies: the way PEAR works goes quite against this point, as pear dependencies are installed system wide and usually you don't have a consolidated manifesto to declare them. Is also usual for a PHP setup to require you to add packages to your OS installation to get some libraries available. Finally AFAIK there isn't a tool in PHP to provide isolation like "virtualenv", "rbenv" or "rvm" (or if it exists is not popular among the PHP community) Edit: Composer (http://getcomposer.org/) seems to do the right regarding dependencies, it still doesn't isolate the PHP version, but for all the rest it should be fine.
Config: some PHP frameworks are not very well suited to do this, but there are certainly others that do well, so it's not a flaw of the platform itself
Backing Services: shouldn't be much of an issue, despite maybe having to hack some frameworks a little in order to manage the services as resources
Build, release, run: this is totally appliable to PHP as this definitively doesn't concern only "compiling". One may argue that several projects and hosting platforms on the PHP community abuse of direct FTP, etc. but that's not a flaw of PHP itself, and there is no real impediment on doing things right regarding this item.
Processes: This definitively concerns to PHP. PHP is quite capable of running purely stateless processes (the emphasis is on the word stateless), and actually several frameworks make your life easy for it. For example, symfony provides out-of-the-box session management with memcached or database storage instead of regular sessions
Port binding: Over simplyfing it, this point basically demands you to reverse proxy and have the actual webserver embedded on the app instead of being a separated component. This puts PHP in a very hard position to comply. Despite there are ways to do this (see the reply about using PHP as FastCGI) that's definitively not the most common nor the best supported way to serve a PHP app as it is on other communities (e.g. Ruby, Node.js).
Processes: This is not impossible in PHP. However several elements put PHP in a hard position to comply. Namely the lack of good support for items 6 and 7; the fact that the PHP API to spawn new processes isn't really very nice to work with; and specially the way Apache's mod_php handles their workers (which is by far the most common deployment schema for PHP)
Disposability: If you use the right tools there is nothing inherent on PHP to prevent you from creating fast, disposable, tidy web and worker processes. However I believe that since the underlying process model is hard to implement as per points 7 and 8, then 9 becomes a bit cumbersome as a side effect
Dev/prod parity: This is very platform agnostic, and I would say one of the hardest to get done right. PHP is no exception to this rule, but it doesn't have a particular impediment either. Actually most of the tools named on the manifesto can be applied to a PHP project
Logs: Having your app agnostic of the log system on the execution environment is totally doable on PHP
Admin processes: The most important flaw of PHP regarding this point is its lack of a REPL shell. Regarding the rest, several frameworks like Symfony allow you to program admin tasks (e.g Doctine-based database migrations) and run them on the same environment as your "regular" web envionrment.
Since the PHP community is evolving, it may be that it has already righted some of the wrongs mentioned.
Build, release, Run: Applicable to compiled code which is not the case in PHP. So this
point is not something you need to look at.
I don't claim any authority on this 12 factor stuff, but my read of that section is that the author would disagree. It's not just about compiling, it's about managing dependencies both in the small (the snapshot of the code) and in the large (any libraries the code uses).
Imagine you're a new dev and they say, "Okay, this is a custom php app, so...
a) The custom code is really two subprojects, which are in repo A and repo B.
b) You'll need to create a directory layout like so, and then
c) check the code for each subproject out into this subdirectory and this subdirectory.
d) You'll also need these three open source PHP libraries:
version 3.1 of library Foo,
version 2.3 of library Bar, and
version 5.6 of library Bat.
e) download them from their home project sites and unpack them, then copy them into this directory, that directory, and the other directory.
f) then you'll need to set these configurations in the external library,
g) and these configs in our two custom code projects.
h) once that's all done, tar/gzip it all up, upload it up to the QA server and untar it into htdocs.
There's no compiling going in that set of steps, but you can bet there's a lot of building.
Getting all of that set up and working is the build step.
Using tar/gzip to take a snapshot of the working build is the release step.
SCP'ing/unpacking it into the QA server's htdocs directory is the runtime step.
You might say that some of those steps above are unnecessary - the libraries should be deployed at the system level and merely imported. From the 12factors.net site I'd say the author prefers you to import them uniquely and individually for the app. It sidesteps dependency versioning problems at the cost of more disk space (not that anybody cares). There are more hassles in managing all those dependencies as local-to-the-app, but then that's the point of the build/release/runtime scheme.
It might have changed since you read it - there are a few PHP examples now, although a few of them seem like negations of the twelve-factor concept.
One of the ways that normal mod_php sites violate twelve-factor comes with VII. Port binding. From the manifesto:
The twelve-factor app is completely self-contained and does not rely on runtime injection of a webserver into the execution environment to create a web-facing service. The web app exports HTTP as a service by binding to a port, and listening to requests coming in on that port.
However, apache/php can be coaxed into this worldview with something like this:
https://gist.github.com/1398498
Not perfect, but it works for the most part. To test it out, install foreman:
gem install foreman
then run it in the directory you cloned the gist into:
foreman start
then visit
http://localhost:5000/foo
DO NOT TAKE THIS POST AS A REFERENCE, THIS WAS WRITTEN IN 2011, MANY THINGS HAVE CHANGED SINCE THEN... THE WORLD OF PROGRAMMING IS IN CONSTANT EVOLUTION. A POINT OF VIEW OF 2011 IS NOT NECESSARILY STILL VALID IN 2018.
I just read a few lines of each points and here goes my analysis of the document:
Codebase: Everyone, php or not should have a codebase even for the little projects
Dependecies: PHP uses includes and code libraries that you should always be able to port easily by simply copying the code to a server. Sometimes you use PEAR and then if the server doesn't support it, you have to copy and install pear manually. I use Zend Framework most of the time, so it's just copying the code of the framework with the ftp upload.
Config: It is common for php apps to have a writable config file that you store configurations into. Where you store it is your choice as a developer, but it is usually either at the root of your app or in a settings/config folder.
Backing Services: PHP does use backing service most of the time such as MySQL. Other common services depending on your app are twitter and facebook. You use their API to communicate with them and store/retrieve data to work with.
Build, release, Run: Applicable to compiled code which is not the case in PHP. So this point is not something you need to look at.
Processes: HTTP is stateless and is SERVED,thus, you usually have no process apart from the web server. This is not entirely true as a webservice may be bundled with applications you package with or create for it. But, for the sake of standards, you usually don't have to use processes in the web world.
Port binding: PHP doesn't apply to port binding at all because it is not a process that hooks to an address, Apache, NGinx or Lighttpd does that for you. Reading #6/7 makes me understand that a website could never be a Twelve-Factor app.
Concurrency: Again this point treats about processes which do not apply to PHP web pages. This point applies to the server serving the content.
Disposability: This point discusses about how fast a process should be. Obviously, PHP web sites not being a process shouldnt apply but always note that your website should execute pages as fast as possible... Always think about this block or that block of code and see if it is optimized.
Dev/Prod Parity: This point is crucial in any app development. You never want to have a large gap between two app versions or upgrading can become a hassle. Furthermore, never create client specific versions of an app. Always find ways to allow your app to be configured/customized at the template level so you can keep your app as close as possible to all installed versions everywhere.
Logs: Logs are always a good thing to have, they allow you to follow the process of your code without having to output it to screen. My favorite tactic is to "tail -f logfile" inside of a linux console and look at what is happening as i execute my code.
Admin processes: Not applicable, in php, you don't have processes, but you do have pages that you can secure with usernames and passwords.

Executing Actionscript on a linux server

I have a set of ~5 ActionScript 3 classes that are currently used within a flex 4 application. Although their output is used to display graphs etc in my flex app, the classes themselves have no visual components - they are only used to do complex math computations (I originally implemented them in AS3 in order to avoid constant server calls when computations were needed by the flex app).
However, I now want to make the same mathematical computation engine available on my linux server so the computations can be done within PHP. Is there any way at all to access the logic in these classes on the server? I would really like to avoid re-implementing the complex logic in PHP.
Thanks so much for any help you can give!
How many lines of code in your AS3 classes, and what kind of load do you need to handle?
If you're building anything for more than one-off use then the easiest route is probably porting your ActionScript to JavaScript. There aren't any automated converters that I know of but JavaScript and AS3 are so similar that unless your five classes have thousands of lines of code you should be able to make short work of it. Once you've ported it to JavaScript it'll be trivial to run in Node.js, directly through the VM of your choice, or even in the user's browser.
If you only need this to scratch and itch or for limited use you may be able to get away with running AS3 directly in Tamarin or redtamarin. However as far as I know neither of these are currently suitable for production use.
If you are using this in a high-availability, high traffic PHP app, however, I think you'll experience a lot less pain in the long run just porting your code to PHP. AS3 and PHP are similar enough in syntax that you could probably just do a straight port.
Finally, you can find some further discussion and links in this thread: Is it possible to create a 'command line' swf?
You can use redtamarin
http://code.google.com/p/redtamarin/
from a Linux server standpoint you will be able to run
your AS3 source code as CGI (either the AS3 script directly or compiled as ABC)
or you can also bundle your AS3 code into an exe that you will then call via PHP
or make your AS3 script as executable with binfmt_misc
http://code.google.com/p/redtamarin/wiki/RunningShellScripts#Registering_an_extension_as_non-native_binaries_(Linux_only)
here on production and development servers we use redtamarin
as scripts, to do our SVN hooks, automate tasks on linux servers etc.
as socket servers, http servers and CGI
as executable to reuse AS3 logic into our automated builds
etc.
look a bit in the documentation you will see you have a lot of options
to reuse your AS3 code: stdin/stdout/stderr, sockets, pipes, CGI, etc.

php socket programming,Pros and cons and Approach

I am working on a task where it is required to distribute live data (being fetched from some other server) to client using sockets. We user drupal as a framework and thus my choice of PHP.
1)I want to know the major factors that should be taken into consideration while developing this server.Like security,authentication,load etc and how should i approach this.Is there any blog/article that could be of help.
2)Is there a better choice than PHP for this?
3)ALSO is there any drupal module that could assist me in this.
I can think about one issue when you are talking about several servers connecting to you, you may want to conceder a nonblock mode.
Because when you are working with blocking mod, each server can connect at the time, meaning that there will be delay delivering the message.
http://il2.php.net/manual/en/function.socket-set-nonblock.php
I think java would be better choise, multi thread may help here.
from my point of view, this is something that you need to develop your self, socket programming needs a lot of attention.
Drupal is a Web CMS, it can be used as framework for advanced web features or light to medium web application that fits well in the traditional HTTP request paradigm. IMHO, distributing live data from multiple servers to client using sockets doesn't fit with the base assumption behind Drupal's design.
PHP can be used to write socket server. It used to be un-common, but it is becoming more and more available. ReactPHP is a non-blocking I/O library/framework suited for socket programing. Racthet is a websocket server in PHP using ReactPHP.
In any case, this would ne nothing like developing a web application with RoR, Drupal, Django, Symfony, etc.
If integration with a Drupal website is required, the Service module is a nice solution to provides a REST or XML-RPC API. Or course, direct access to Drupal's MySQL database is also an option but will probably require more knowledge of the used Drupal modules since you will have to replicate their behaviors and understand how they manage their data (for instance, how a particular CCK field is stored in your database).
Note: Previous version of this answer included reference to the following solutions in other languages: Twisted (Python), EventMachine (Ruby) and Node.js (JavaScript). These are all valid solutions when PHP is not required.
Previous version of the answer also referenced phpsocketdaemon, but nowadays ReactPHP is a more clean and robust solution.

How to connect Jms from PHP ?

I am trying to implement my sites little chat function like facebook uses. I used Html, PHP, JQuery and Apache. I made before some exaples with JMS but I couldn't figure out how to send message to a JMS server with PHP?
For JMS I used Weblogic.
You have a few options. Let's go through them in order of worst to not-worst.
First is Quercus, a PHP implementation in Java. PHP code running in Quercus can instantiate Java classes and call methods on them, just like they were PHP objects. You'd be able to work with JMS in the same way you'd work with it in Java. I have no experience with this one.
Second is the PHP/Java Bridge. It's a bit more complex to get working, but it effectively works the same way as Quercus, code-wise. You'd be able to work directly with any old Java API. I have experience with this one, and it wasn't pleasant. Java processes ended up hanging around in a zombie state after the corresponding Apache+PHP child exited. We eventually had to write a cron script to clean up all working Java processes nightly, otherwise the server would eventually run out of available memory.
Third would be looking at different JMS providers, like ActiveMQ. Why? Because ActiveMQ supports many messaging APIs, including Stomp, a language-agnostic messaging API that happens to have a PHP extension. It's possible that Weblogic can speak Stomp, but I was unable to determine if this is the case. The only Google results were for Weblogic + ActiveMQ integration.
Fourth would be not thinking about JMS. JMS is a Java solution. PHP ain't Java. There are plenty of message queue systems out there that work well with PHP. ActiveMQ is only one example. I personally prefer Gearman. Gearman was originally designed to perform sharded remote procedure calls, but it works equally as well for simple message passing, and has a PHP extension as well as bindings for most other languages under the sun.
Just to give two other options: OpenMQ (using HTTP) and PHPMQ
(My two cents about the accepted answer)
Great answer, one quibble: Gearman is great for Remote Procedure Calls, but as to message passing, JMS is much more robust (persistence, etc.). Aim for JMS in some way would be my suggestion.

Categories