ORM Designer 2

I thought I’ll help plug a tool that looks to be quite useful and that is basing their development on direct community input, I’ve made my suggestions hope you do too 🙂

Martin Kulhavy writes; ORM Designer. It’s primary target is to create ORM Definitions fast and easily with the help of visual diagram instead of manually written text definitions.
Most distinctive features allows you to:
  • Save time and work 4 times faster.
  • Repeatedly export your definition files.
  • Import and visualize existing project schemas.
  • Eliminate errors and the need to look for typos.
Download our 14-day trial version and let us know what you think. If you write a review, we will give you 20% discount off the price of ORM Designer. Either way, let us know, what you think about it. If you found it helpful, and if not, why not. Any feedback is incredibly valuable to us, as we strive to make our product the best we possibly can.

Running ZendServerGateway on the embedded PHP 5.4 Server

Michael Andrew Davidson writes; So you have discovered ZendServerGateway and you are like, “Wow, this makes web services easy”. However, you quickly discover that there is a little magic behind the scenes, and that this add-on works best within the context of Zend Server 6. That can be a little frustrating, especially if you or your organization does not use Zend Server 6. Never fear, there is a way around this “implied” requirement. In just a moment I will walk the reader through setting up the embedded PHP 5.4 webserver to utilize the ZendServerGateway. All the steps should easily translate to whatever environment you use for serving your PHP pages. I am going to assume a Window environment for development.

read the rest Michael Andrew Davidson’s Blog.

Module specific layouts in ZF2

Rob Allen writes; If you need different layout scripts to be rendered for different modules in Zend Framework 2, then Evan Coury has made this extremely easy. His new module EdpModuleLayouts is just the ticket!

Once installed, you simply have to add a new array to a config file in the config/autoload folder with the following in it:

array(
'module_layouts' => array(
'Application' => 'layout/application',
'ZfcUser' => 'layout/user',
),
);

i.e. you provide a list of the module name against the layout script to use.

What could be easier?

via Rob Allen’s DevNotes.

PHP: Type Hinting – Manual

Found this little Gem today by  Daniel dot L dot Wood at Gmail dot Com;

People often ask about scalar/basic typehints.  Here is a drop in class that I use in my MVC framework that will enable typehints through the use of a custom error handler.

Note: You should include this code above all other code in your include headers and if you are the using set_error_handler() function you should be aware that this uses it as well.  You may need to chain your set_error_handlers()

Why?
1) Because people are sick of using the is_* functions to validate parameters.
2) Reduction of redundant coding for defensive coders.
3) Functions/Methods are self defining/documenting as to required input.

Also..
Follow the discussion for typehints in PHP 6.0 on the PHP Internals boards.

[cc lang=”php”]
< ?php define('TYPEHINT_PCRE' ,'/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/'); class Typehint { private static $Typehints = array( 'boolean' => ‘is_bool’,
‘integer’ => ‘is_int’,
‘float’ => ‘is_float’,
‘string’ => ‘is_string’,
‘resrouce’ => ‘is_resource’
);

private function __Constrct() {}

public static function initializeHandler()
{

set_error_handler(‘Typehint::handleTypehint’);

return TRUE;
}

private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue)
{

foreach ($ThBackTrace as $ThTrace)
{

// Match the function; Note we could do more defensive error checking.
if (isset($ThTrace[‘function’]) && $ThTrace[‘function’] == $ThFunction)
{

$ThArgValue = $ThTrace[‘args’][$ThArgIndex – 1];

return TRUE;
}
}

return FALSE;
}

public static function handleTypehint($ErrLevel, $ErrMessage)
{

if ($ErrLevel == E_RECOVERABLE_ERROR)
{

if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches))
{

list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches;

if (isset(self::$Typehints[$ThHint]))
{

$ThBacktrace = debug_backtrace();
$ThArgValue = NULL;

if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue))
{

if (call_user_func(self::$Typehints[$ThHint], $ThArgValue))
{

return TRUE;
}
}
}
}
}

return FALSE;
}
}
Typehint::initializeHandler();
?>
[/cc]
An are some examples of the class in use:
[cc lang=”php”]
< ?php function teststring(string $string) { echo $string; } function testinteger(integer $integer) { echo $integer; } function testfloat(float $float) { echo $float; } // This will work for class methods as well. ?>
[/cc]

You get the picture..
via PHP: Type Hinting – Manual.

ClamAV as a Validation Filter in Zend Framework

Matthew Setter writes a very interesting article; Ok, so you’re pretty comfortable with using the Zend Framework, specifically the use of Forms. Along with that, you have a good working knowledge of how to combine a host of standard validators such as CreditCard, EmailAddress, Db_RecordExists, and Hex, and standard filterssuch as Compress/Decompress, BaseName, Encrypt, and RealPath. But what do you do when a situation arises that’s outside the scope of the pre-packaged validators and filters?

Let’s say you want to guard against users uploading files that contain viruses, for example. You would have to write a custom validator that checks the uploads aren’t infected. Today I’ll show you how to do just that – how to write a new file validation filter for Zend Framework that uses ClamAVto ensure uploaded files are virus-free.

Adding ClamAV Support to PHP

First you’ll need to install ClamAV support. I’m basing this installation procedure around Linux, specifically Ubuntu. If you’re using another distribution, you may need to adjust the commands accordingly. Unfortunately, if you’re using Windows however, you’ll need to use a Linux-based Virtual Appliance or setup a virtual machine running Linux to follow along since the php-clamav extension doesn’t support Windows as yet.

Full Story with Source » phpmaster.

Zend Server 5.6 is out

Kevin Schroeder writes; Zend Server 5.6 is out.  I’m actually pretty stoked about this release.  Here’s a few reasons why.

  1. Zend Server CE now contains the full Zend Server stack.  Why do I find this exciting?  Because the upgrade path from CE to the full version is stupid easy.  That means you can try out all of the features in Zend Server and if you don’t want them, just let the license expire.  I call it a gateway drug.  Seriously.  Get Studio or PDT and try the deployment feature.  If you’re not using it you’ll ask yourself “why am I not doing this?”
  2. All of you Mac users can finally stop bitching and complaining about the lack of Mac support.  We don’t (and probably won’t) support Mac for production (does anyone besides Apple actually use their server products in production?) but for dev work you now get the full stack on your Mac.  This is not GA yet but will be later on.  If you want a preview release you can go to http://forums.zend.com/viewtopic.php?f=8&t=26873 .
  3. Fault tolerance in the Job Queue through MySQL clustering.  In clustered environments job queue information has moved from local storage to remote MySQL storage.  So you can have a single MySQL server sitting there, a clustered setup or RDS or some other cloud-based DB, it doesn’t matter.  If it can be accessed using the MySQL drivers then it can be used by the new Job Queue.

via ESchrade – Pure PHP Goodness.

Connecting to PHPCloud.com through Zend Studio 9

PHPCloud.com is the landing page for our new cloud offering.  Using the Zend Application Fabric you can build your applications in the same environment as you will be deploying your apps to.  The application is built on my.phpcloud.com and you can then deploy it onto any platform where the Fabric is supported.

But how do you get started?  Phpcloud.com has been built in a way where you can connect with any IDE.  With Zend Studio 9 that connectivity has been built directly in to the IDE.

Getting started is actually quite easy.

via Read here for the full details.

Zend AMF Authentication & Authorization

dkozar evolved a working method to Authenticate and Authorize a Flex based app datas service call using Zend AMF, he writes;

I’ve been struggling with it, and figured it all out – so, perhaps it could help others.

The authentication is called on the server only if credentials supplied from the client (via the remote procedure call headers). This snippet illustrates the setup of custom auth (these are the last 6 lines of gateway.php script):

// Handle request
$auth = new My_Amf_Auth(); // authentication
$server->setAuth($auth);
$acl = new Zend_Acl(); // authorization
$server->setAcl($acl);
echo $server->handle();

Now, your custom auth should extend Zend_Amf_Auth_Abstract. Since I want to authenticate users from a database, I bring the Zend_Auth_Adapter_DbTable to play. But since I cannot extend both Zend_Amf_Auth_Abstract and Zend_Auth_Adapter_DbTable, I use a composition:

< ?php require_once ('Zend/Amf/Auth/Abstract.php'); /** * AMF auth class by Danko Kozar, dankokozar.com * @author dkozar * */ class My_Amf_Auth extends Zend_Amf_Auth_Abstract { function __construct() { } public function authenticate() { $adapter = My_Db_Adapter::getInstance(); $adapter->setIdentity($this->_username);
$adapter->setCredential($this->_password);

// the adapter call
// you can wrap it into try.. catch and process DB connection errors
$result = Zend_Auth::getInstance()->authenticate($adapter);

return $result;
}
}

Here’s the adapter class:

< ?php /** * DB table adapter auth class for AMF by Danko Kozar, dankokozar.com * @author dkozar * Singleton */ class My_Db_Adapter extends Zend_Auth_Adapter_DbTable { protected static $_instance = null; /** * private! * @param My_Db_Adapter $adapter */ public function __construct(Zend_Db_Adapter_Abstract $adapter = null) { if (!$adapter) $adapter = new Zend_Db_Adapter_Mysqli( array( 'dbname' => 'test',
'username' => 'root',
'password' => '')
);

parent::__construct($adapter);

$this
->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
;

// just for testing
// $this
// ->setIdentity('username')
// ->setCredential('password')
// ;
}

/**
* @return My_Db_Adapter
*/
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}

public function authenticate() {

$_authResult = parent::authenticate();

// NOTE: The point is that $result->_identity is an OBJECT (of type stdClass), NOT string
// with Zend_Auth_Adapter_DbTable it is internally accomplished by calling its getResultRowObject() method
// It constructs the stdClass with properties named after table attributes

// $user = new stdClass();
// $user->role = "administrator";
// $user->username = $_authResult->getIdentity();

$identity = $this->getResultRowObject();

$result = new Zend_Auth_Result($_authResult->getCode(), $identity);

return $result;
}
}

MyService.php class. Here it is:


< ?php /** * PHP service class with authorization * by Danko Kozar, dankokozar.com * @author dkozar * */ class MyService { /** * from zend docs: * If the ACL object is set, and the class being called defines initAcl() method, * this method will be called with the ACL object as an argument. * This method can create additional ACL rules and return TRUE, * or return FALSE if no access control is required for this class. * * @param Zend_Acl $acl * @return boolean */ public function initAcl($acl) { $acl->addRole(new Zend_Acl_Role("administrator"));
$acl->addRole(new Zend_Acl_Role("user"));

//acl "allow" method takes 3 parameters (role, resource - class name, privileges - it's function name in this class)

// administrator
$acl->allow('administrator', 'MyService', 'helloWorld');
$acl->allow('administrator', 'MyService', 'getData');

// user
$acl->allow('user', 'MyService', 'helloWorld');
$acl->deny('user', 'MyService', 'getData');

//returning true to signal that we want to check privileges before accessing methods of this class
//in my tests if we don't return anything it will treat it like we will return false so better return true or false
//your intentions will be clear
return true;
}

/**
* Hello world method
*/
public function helloWorld(){
return "Hello world from MyService service";
}

/**
*
* Returns data
* @return [int]
*/
function getData()
{
$arr = array(1, 2, 3);
return $arr;
}
}
?>

Note that the authorization is being built dynamically inside the initAcl method.

On the Flex side I have an auto-generated class (MyService) which extends another auto-generated class (_Super_MyService).

The point is that the outer one is auto-generated only once (initially), and you can modify it, without worrying to be overwritten on service regeneration.

There’s a protected property _serviceControl (which is of type RemoteObject) which could be tweaked if needed.

I’m tweaking it by of setting the endpoint (with string read from a client side config in preInitializeService() method). Plus, I’m adding 2 more methods, which expose setCredentials and setRemoteCredentials methods of _serviceControl, so I can acces it from my code.


package services.myservice
{
public class MyService extends _Super_MyService
{
/**
* Override super.init() to provide any initialization customization if needed.
*/
protected override function preInitializeService():void
{
super.preInitializeService();

// Initialization customization goes here
_serviceControl.endpoint = "http://localhost/myapp/gateway.php";
}

public function setCredentials(username:String, password:String, charset:String=null):void
{
_serviceControl.setCredentials(username, password, charset);
}

public function setRemoteCredentials(username:String, password:String, charset:String=null):void
{
_serviceControl.setRemoteCredentials(username, password, charset);
}
}
}


So, before calling MyService methods, I’m setting the credentials with setCredentials() method and this runs the authentication on the PHP side:


private var service:MyService;
....
service = new MyService(); // ServiceLocator.getInstance().getHTTPService("presetLoader");
service.setCredentials("user1", "pass1");
var token:AsyncToken = service.getData();

The authentication via Zend_Amf_Server is, by the way, OPTIONAL! Meaning, with no credentials supplied, Zend_Amf_Server will NOT RUN IT. Thus you should rely on Zend_Acl (e.g. roles) to so your permissions and security!

Finally, here’s the MySQL DB table I’ve been using for authentication:

--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(32) DEFAULT NULL,
`role` varchar(45) DEFAULT NULL,
`firstname` varchar(50) DEFAULT NULL,
`lastname` varchar(50) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `role`, `firstname`, `lastname`, `email`) VALUES
(1, 'user1', 'pass1', 'administrator', 'Danko', 'Kozar', NULL);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cheers!
Danko

Adobe Forums

Authentication using Zend_Amf

Kevin Schroeder writes; I forget why, but a few days ago I started doing some digging around with authentication in Zend_Amf_Server. I had figured that I would add an adapter to the Zend_Amf_Server::setAuth() method and that would be it.

But I was wrong.

AMF allows for multiple request bodies to be sent at the same time. Of those there are several “special” types of commands. One of those commands is logging in. What this means is that you don’t need a method that logs someone in for you. Zend_Amf_Server handles authentication separately from your service classes.

Authentication for Zend_Amf_Server will generally use a combination of Zend_Auth and Zend_Acl components. Zend_Auth is used to provide the credential verification while Zend_Acl is used to validate that the current user user can access the requested service method. It is actually a relatively trivial task to restrict access to non-logged in users using the method that I will describe here.

The first step in the process is to create an authentication adapter. It really doesn’t matter what you’re using. What matters is that the adapter returns an identity object with a property called “role”. The built in ACL handle expects this to be part of the identity object.


class Auth extends Zend_Amf_Auth_Abstract
{
const LOGGEDIN_ROLE = 'loggedin';

public function authenticate()
{
$identity = new stdClass();
$result = Zend_Auth_Result::FAILURE;

// Do a proper login, y'all
if ($this->_username == 'test' && $this->_password == 'test') {
$identity->role = self::LOGGEDIN_ROLE;
$result = Zend_Auth_Result::SUCCESS;
} else {
$identity->role = Zend_Amf_Constants::GUEST_ROLE;
}

return new Zend_Auth_Result($result, $identity);
}
}

The Auth class extends Zend_Amf_Auth_Abstract because Flex seems to require username and passwords as being the only mechanism for passing credentials. The abstract class defines a method that hooks in with the special commands and passes the special credentials to the special adapter. Clearly your authentication mechanism should be better than the one that I put in here, but you’ll get the idea. The most important part is adding the role property to the identity object and passing it to the Zend_Auth_Result object.

Then in your gateway you need to add this adapter as well as create an simple ACL.


$server = new Zend_Amf_Server();
$server->addDirectory(realpath(__DIR__.'/../services'));

$acl = new Zend_Acl();
$acl->addRole(Auth::LOGGEDIN_ROLE);
$acl->allow(Auth::LOGGEDIN_ROLE);
$server->setAcl($acl);

$auth = new Auth();
$server->setAuth($auth);

echo $server->handle();

This adds the new Auth role to the ACL and says that it has access to everything. Since there is no place where I allow guest access (denoted by Zend_Amf_Constants::GUEST_ROLE in the adapter) guest requests will be denied.

With just this little bit of code you now have a mechanism that will provide restricted access to all of your service objects.

via Kevin Schroeder’s blog – Zend Technologies.