Skip to content

Custom php functions

ccapndave edited this page Apr 11, 2011 · 6 revisions

Flextrine allows you to run your own PHP functions on the server, and return a result if required.

In the PHP server-side application

Create the function you want to run within your server-side FlextrineService.php file. For this example we'll create a simple function that takes a string, and returns that string plus the current server time. It is important to mark your function public otherwise Flextrine won't be able to access it.

<?php
public function getServerTime($label) {
  return $label." ".date("F j, Y, g:i a");
}

Note that you have access to the Doctrine EntityManager via $this->em if you want to perform ORM operations in PHP.

In the Flex client-side application

In Flex you call a custom server-side function using the callRemoteMethod method of EntityManager. This method returns an AsyncToken which you can use to listen for an asynchronous result.

em = EntityManager.getInstance();
em.callRemoteMethod("getServerTime", "The time is:").addResponder(new AsyncResponder(onResult, onFault));

private function onResult(result:Object, token:Object):void {
  trace("Received result: " + result);
}

private function onFault(fault:Object, token:Object):void {
  throw new Error("An error occurred whilst calling the custom remote method: " + fault);
}

If you are not interested in the result (and don't care if there is a fault) it is perfectly fine to just ignore the return value of callRemoteMethod.

em.callRemoteMethod("doSomethingInPHP");

Calling methods on different services

For larger projects it might make sense to create more services in the services directory, instead of having everything in the default FlextrineService. To call a method on a specific service use the format <service>.<method> in callRemoteMethod:

em.callRemoteMethod("MailService.sendMail", title, subject);

Calling methods that return entities

In some situations you will want to work directly with Doctrine's EntityManager in PHP and return the result to Flextrine. In this case we want Flextrine to perform its normal processing on the entity, so a special method callRemoteEntityMethod is available. Its syntax and usage is identical to callRemoteMethod:

em.callRemoteEntityMethod("getUser", "[email protected]");
<?php
public function getUser($email) {
  $user = $this->em->getRepository('vo\User')->findOneBy(array("email" => $email));
  return $this->flextrinize($user);
}

Notice that we run the entity through $this->flextrinize on the server before returning it. This performs some server-side processing on the entity so that Flextrine can deal with it correctly, and is essential.

callRemoteEntityMethod will be available from Flextrine 0.9.1 onwards.