WebConsults.EUQuicksearchKategorien |
Monday, March 29. 2010PHP 5 Reflection access privat methods
There were highly idiologic discussions about if you should test your privates or not with unit testing or not,
in my opinion especially during Development with private methods performing for example calculations it could be useful to Unit Test these.
At least during development you make sure that these functions already work, and finally it´s better to change accessibility than just to set accessibility lower to make testing possible. Before PHP 5.3.2 it was not possible to change the accessibility but with the new ReflectionMethod it is.
But this feature needs to be used with care, it´s made for unit testing and maybe very special other cases wich are not in my mind yet.
Using some magic reflection stuff always makes code very hard to read, maybe you think it´s fance but others might get confused a lot.
Using the ReflectionMethod introduced in PHP 5.3.2 ReflectionMethod::SetAccesible ReflectionMethod Class PHP Unit Developer Sebastian Bergmann wrote an article about Testing Your Privates Sebastians Bergmanns Example: <?php class FooTest extends PHPUnit_Framework_TestCase { public function testPrivateMethod() { $method = new ReflectionMethod( 'Foo', 'doSomethingPrivate' ); $method->setAccessible(TRUE); $this->assertEquals( 'blah', $method->invoke(new Foo) ); } } ?> Tuesday, March 23. 2010Fake Zend Framework isXmlHttpRequest for Unit Testing
To manipulate the result Zend_Controller_Request_Http::isXmlHttpRequest()
maybe for testing XML Controllers in PHP Unit you just need to set the HTTP_X_REQUESTED_WITH value to XMLHttpRequest
Zend_Controller_Request_Http::isXmlHttpRequest() does nothing more than checking for this.
$_SERVER['HTTP_X_REQUESTED_WITH']="XMLHttpRequest"; public function isXmlHttpRequest() { return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest'); } public function getHeader($header) { ........ $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header)); if (!empty($_SERVER[$temp])) { return $_SERVER[$temp]; } Monday, February 8. 2010Dynamic Model for Zend Framework
I always liked some kind of auto generated model to access a database.
I liked it the way Symfony does or the Zend Framework Tool.
But anytime using a generator is also a bit of mess.
The actual Zend Framework quickstart example has a 3 files way of implementing a Model, a Model Class, Model Mapper Class and Model DB Table ClassFew,
so for one DB Table you always have to create 3 classes which look almost similar, most times you just copy and paste those, and change a few things.
So i decided to create an very flexible model class, where you just need to define the properties and nothing more getter and sette methods will be called by magic functions. Even it has export function to an array.
You don´t have to create anything but you can create your own functions for getter and setter methods which would override the default ones.
In later state it could be possible to add a filter configurable in the model, but for first step i would like to keep it as slim as possible.
class Dynmodel_Model { protected $_id; protected $_created; public function __construct(array $options = null) { if (is_array($options)) { $this->setOptions($options); } } // // Magic Call function // @param <type> $name // @param <type> $arguments //@return <type> // public function __call($name, $arguments){ if(substr($name,0,3)=="set"){ return $this->__set(substr($name,3),$arguments[0]); } if(substr($name,0,3)=="get"){ return $this->__get(substr($name,3)); } throw new Exception('Method '.$name.' not Supported'); } // // Magic Setter Class // @param <type> $name // @param <type> $value // public function __set($name, $value) { $method = 'set' . $name; $propertyName="_".lcfirst($name); if(method_exists($this, $method)){ method_exists($this, $method); }elseif (('mapper' == $name) || !property_exists($this, $propertyName)) { throw new Exception('Invalid Property '.$propertyName); }elseif(property_exists($this, $propertyName)){ $this->$propertyName=$value; } } // // Magic getter class // @param <type> $name // @return <type> // public function __get($name) { $method = 'get' . $name; $propertyName="_".lcfirst($name); if(method_exists($this, $method)){ return $this->$method(); }elseif (('mapper' == $name) || !property_exists($this, $propertyName)) { throw new Exception('Invalid Property '.$propertyName); }else{ return $this->$propertyName; } } public function setOptions(array $options) { $methods = get_class_methods($this); foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); if (in_array($method, $methods)) { $this->$method($value); } } return $this; } // // Returning the Objects as Array // @return Array // public function toArray(){ $values=array(); foreach(get_object_vars($this) as $pkey => $pvalue){ if(substr($pkey,0,1)=="_"){ $arrkey=substr($pkey,1); $call="get".ucfirst(substr($arrkey,1)); //calling value through objects get function $values[$arrkey]=$this->$call(); } } return $values; } } Thursday, January 21. 2010Zend Framework PHP based SOAP Server with Java JAX-RPC client
This example shows how to create an Zend Framework based SOAP Server and connect to it by a Java Client. The process itself is really easy but some things ara a bit tricky for example at the status were i created it there were some problems if using WS style for the SOAP Server so i decided to use RPC style. The Server basically allows a user to logon by credentials and gives back a userstatus, the Java Client is connecting through this service and requesting the userstatus.
The Soap Server Class
<?php // orginal code has phpdoc compatible comments with slash star // // SoapUserServer Class // // @author // // // Description of SoapUserServer // // @author johny // class Example_SoapUserServer { // // // Returns Api Version // @return string getApiVersion // public function getApiVersion() { $apiVersion="0.9.3"; return $apiVersion; } // // getUser // Returns user Status for a given Username, Password combination // @param string $username // @param string $password // @return string getUserResponse // public function getUser($username, $password){ $adapter = new Example_AuthAdapter($username,$password); $userStatus=false; //retrive login $auth = Zend_Auth::getInstance(); $auth->authenticate($adapter); $acl = new Zend_Acl($auth); if (!$auth->hasIdentity()) { //user not valid $userStatus=false; }else{ //user okay //@todo dynamic membership types $membership=$auth->getIdentity()->getMembership(); if($membership && $membership->getMembershipTypeId()>=1){ $userStatus="premiummember"; }else{ $userStatus="normalmember"; } } if($userStatus!=false){ return $userStatus; }else{ return "wrong credentials"; } } } ?> <?php class SoapController extends Zend_Controller_Action { // // Zend Soap Server Action // Representing the soap Server /// public function serverAction(){ if(isset($_GET['wsdl'])) { $autodiscover = new Zend_Soap_AutoDiscover(); $autodiscover->setBindingStyle(array('style' => 'rpc')); $autodiscover->setClass('Example_SoapUserServer'); $autodiscover->handle(); exit; } // disabling WSDL cache cause we are still in Development ini_set("soap.wsdl_cache_enabled", "0"); $server = new SoapServer('http://example.com/soap/server?wsdl'); $server->setClass('Example_SoapUserServer'); $server->handle(); $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); } } ?> package eu.webconsults.myapp.userauth; import java.rmi.RemoteException; import myapp.userauth.Example_SoapUserServerPort_Stub; import myapp.userauth.Example_SoapUserServerService_Impl; // // User Authorization class using Soap Server // @author johny // public class UserAuth { String username = null; String password = null; String usertype = null; Boolean isAuthorized = false; Example_SoapUserServerPort_Stub stub; // // Authenticating remote // // @param username // @param password /// public UserAuth(String username, String password) { this.username = username; this.password=password; this.retrieveRemoteUserStatus(); } // // Retriving remote User Status from Stub // @return /// private String retrieveRemoteUserStatus(){ try{ this.usertype = this.getStub().getUser(this.username, this.password); if(!this.usertype.equals("wrong credentials")){ this.isAuthorized=true; }else{ this.isAuthorized=false; } } catch(RemoteException re){ System.out.println("Remote Exception"+re.getMessage()); } return this.usertype; } // // // @return // private Example_SoapUserServerPort_Stub getStub(){ if(this.stub == null){ this.stub=(Example_SoapUserServerPort_Stub) (new Example_SoapUserServerService_Impl().getExample_SoapUserServerPort()); } return this.stub; } // // Getting Username // @return // public String getUsername(){ return this.username; } // // Getting Password // @return // public String getPassword(){ return this.password; } // // Returning Usertype // @return // public String getUsertype(){ return this.usertype; } } Sunday, August 2. 2009Sending and Rendering Emails with Zend Framework
It took me a little while to figure out to solve a standard problem like sending an template or view script as email, the main problem is the original documentation doesn´t show anything about it, just sending email with text from a string, and if you search on the web, you find mostly the same thing or solutions which were not satisfying me.
//Rendering mail template to string $mail_view = new Zend_View(); $mail_view = new Zend_View(); /<strong> </strong> This will only work inside the MVC vontroller and <strong> handle over script path to the email view renderer </strong>/ $mail_view->addScriptPath($this->view->getScriptPaths()); $strMailBody=$mail_view->render('controllername/mail.phtml'); //configuring email $email_recipient_mail="recipient@example.com"; $email_recipient_name="Recipient Name"; $email_subject="Subject for the Email"; $email_sender_email="sender@example.com"; $email_sender_name="Sender Name"; //sending email with Zend_Mail() $mail = new Zend_Mail (); $mail->setFrom ($email_sender_email, $email_sender_email); $mail->addTo ($email_recipient_mail, $email_recipient_name); $mail->setSubject($email_subject); $mail->setBodyText($strMailBody); $mail->send (); Thursday, March 26. 20096 Things that suck at Symfony Framework
1. The .yml YAML format is very vulnerable for type errors, just one space to much and it breaks
2. Version incompatibility, well to upgrade your symfony framework always cause problems and is not to 3. Too much configuration files. Symfony has too much points were you can configure it or overwrite other configuration, so you never can be sure if it works the way you expect. 4. Documentation is hard to search, a bunch of tutorials but no real documentation even not all parts are up to date. for example try to find documentation about "form_remote_tag" a complete searchable function reference would be helpfull. 5. view.yml files, why should i put logic, like that my ajax request has no Layout to a configuration file?, I prefer it where the request is handled. 6. You Always have to clear the cache during develloping, and sometimes you just forget. Well there are very positives things of Symfony Framework but these made me most annoyed during Symfony Development. Tuesday, March 24. 2009Most used Symfony Commands
Here is a list of my most used Symfony command line rool commands
Generate a new module
php symfony generate:module application modelname
Generate Schema from database
php5 symfony propel:build-schema I always build the Schema from the Database, cause it is easier to Maintain the Database than the Schema file, you can use yoru default Database tool e.q. PhpMyAdmin or MySql Workbench, even there is no chance that sombody implements Database changes wich could be overwritten.Generate Model php5 symfony propel:build-model php5 symfony propel:build-forms php symfony propel:generate-module --non-verbose-templates --with-show frontend post TableCamelCase Note: the TableNameCamelCase is using Uppercase letter before any underscore e.q. TableNameExample for table_name_example Tuesday, February 17. 2009Calculating Age in Years in PHP
Well calculating age in PHP seems to be not that big thing
Date calculation is something wich would be a good topic for Programming for Beginners Lesson 2
It is not that much used cause Databases give a lot of nice date calculating functions like MySQL DateDiff or similar function on other Database.
PHP has not had a DateDiff function from home until PHP 5.3, unfortunatelle the PHP Version on server was 5.2.4 so i could not use the PHP DateDiff Function from the new DateTime Functions.
Cause i was a bit lazy i thought it might be easy to find a usefull function to calculate Age in PHP but anything i found was a bunch of useless forum discussions and not 100% correct working answers so i wrote an own one.
//my save method to get age $strBirthdate = "1939-03-01"; $intYearBirth = substr($strBirthdate,0,4); $intMonthBirth = substr($strBirthdate,5,2); $intDayBirth = substr($strBirthdate,8,2); if($intMonthBirth >= date("m") && $intDayBirth >= date("d")){ //last birthday has been this year $intAge=date("Y") - $intYearBirth; }else{ //last birthday this year $intAge=(date("Y") - 1) $intYearBirth ; } //most popular method found on the web $jetzt = mktime(0,0,0,date("m"),date("d"),date("Y")); $geburtstag = mktime(0,0,0,$intMonthBirth,$intDayBirth,$intYearBirth); $alter = intval(($jetzt - $geburtstag) / (3600 <strong> 24 </strong> 365)); return "method 1 $intAge method 2 $alter"; Saturday, September 13. 2008Good Morning at Symfony Camp 2008
Well i finally got some Network access and time to block from symfonycamp 2008 in Holland,
camp has a really nice concept they got 3 big dutch army tents, and 2 other tents with chairs for dinner and the sessions.
Unfortunatelly the typical dutch rain does not make it that comfortable but it s still okay, only some of my clothes got wet and my car got stucked so far. The Sessions of the first day haven´t been that interesting mostly a lot of general talk about symfony, a bit bashing to other Framworks, CMS, ORM-Layers, so until know the most benefit is more in networking and experience exchange directly with people than what you get offered at the sessions.
Monday, August 25. 2008Webconsults at SymfonyCamp 2008
I just signed up Symfony Camp 2008,
a 2 day meeting in the mid of the Netherlands. Interesting not too comercial Symfony Camp with a lot of experts from the Symphony Scene, interesting topics like and "Friday 17.30 Drinks and BBQ", Debugging, symfony performance, Propel vs Doctrine or Lessons learned at Yahoo.
I am not sure yet if i will book a hotel or sleep in the provided dutch army tents.
Monday, August 4. 2008Putting RSS content via simplexml into Symfony/Propel objects
When i tried to read from an rss file to import into symfony i got an error
Fatal error: Call to undefined method SimpleXMLElement::__toString() in ....lib/symfony/plugins/sfPropelPlugin/lib/vendor/creole/common/PreparedStatementCommon.php on line 596While for printing out a string readen by SimpleXML is jost okay, for Symfony it is not. $rsscontent=file_get_contents($rssfeed); $rssfile=simplexml_load_string($rsscontent); foreach($rssfile->channel->item as $rssitem){ $c = new Criteria(); $strName=$rssitem->name; $c->add(ProcuctPeer::Name, $strName); $objProduct=ProductPeer::doSelect($c); $strName=(string)$rssitem->name;
For setting values also the simplexml object of type string works.
$objProduct->setName($rssitem->name)
Friday, July 4. 2008Messages from Ajax Requests
Giving back errors from AJAX requests is not that easy all the time.
One possibility is to give back an Error Message by the AJAX Result,
but this is not that comfortable at any time you have to put an error handling inside your AJAX call which is returning the message to the user.
Another solution are session based error messages for that you have to implement an Ajax error handling class.
For this messages you create a div layer inside your HTML.
<div id="messagefield" style="visibility: hidden;"> <a href="#" onclick="CloseMessageField()">close</a> <div id="messagefieldtext"></div> </div>'; <?PHP if($strMessageText){ echo "<script type='text/javascript'> ShowMessageField() </script>"; } ?>This example is using Prototype. <script language='JavaScript'> function CloseMessageField() { document.getElementById('messagefield').style.visibility = 'hidden'; } function ShowMessageField() { document.getElementById('messagefield').style.visibility = 'visible'; } function RefreshMessageField(){ ajaxRequest=new Ajax.Request('/your/messege/ajax/url', { method:'get', onSuccess: function(transport) { if(transport.responseText.length > 1){ document.getElementById('messagefieldtext').innerHTML=document.getElementById('messagefieldtext').innerHTML+transport.responseText; ShowMessageField(); } } } ); } </script>Now you create an the AJAX Server by just returning simple HTML code instead XML you save some time if(is_array($_SESSION['errors'] && count($_SESSION['errors']) > 0){ //returning the errors foreach($_SESSION['errors'] as $strError){ echo $strError; } //reset the error string $_SESSION['errors']=array(); }Now you can give out Errors to a message window just by adding them to a Session like $_SESSION['errors'][]="There has been an error by saving your entry"or you can even use it to catch PHP Errors by using the set_error_handler function to see the PHP Errors which were thrown during the AJAX request execution. Any time you have a failed AJAX request you just call the RefreshMessageField() function instead from the returned AJAX response messages. Within your AJAX request you just have to differ between successful answer or showing the error message window. This example is a bit simplified i wrote myself an own Error handling class which supports multiple reporting modes which differ between a Development mode and Production mode but this should give you an overview how the process works. Tuesday, June 17. 2008JavaScript Sandbox Proxy in PHP
Well for your website you´ll often have to include external JavaScript like tags of ad partners, external adserver etc.
These foreign JavaScript is always a security risk, if a optional enemy is able to change the external JS he might take effect of CrossSite Scripting on your site. So how to protect against XSS from partners you need to include but which are possibly evil.
Well there might be the solution of a PHP based JavaScript interpreter wich could handle external JS in a server based sandbox,
J4P5 might be a solution to it it makes you able to run JavaScript from your PHP Server so it´s a kind of interpreter to it. Based on your server you need to evaluate the JS generated code if it is not generating possibly eval JavaScript. It might cause some disadvatages like if ad tags try to determine your browser, ip, and maybe some JS scripts are not working of cause will not have a good effect on performance but might prevent some XSS security issues, specially if you include JS from an untrustable third party.
I ll try it out in the next time.
Monday, June 16. 2008DesignPatterns: Factory a bit more Generic
Well the task was type of data should be shown in HTML types, textfields, calendars and so on.
What i created is a FieldType factory which could load a special childclass if it is defined and would otherwise use the standard data class to handle it, this makes it possible to have a standard behavior for new data which might approach later and you don´t have to create a new class at once. Only if a special behavior is wanted you need to create a sub class for your field type.
I used some kind of Factory::Pattern to load the class which is returning the standard class if a child class for the field type is not existing, usually i hate classes or function being called by dynamic names but in this case it is very useful doesn´t mean a security risk cause the class has to be loaded in your php code before and will not bee included by thinks like
include "$classname".php or something
class Field_standard{ public $value=""; ... other functions ... public function getHtmlForm(){ return '<input type="text" name="'.$this->strName.'" value="'.$this->getValue().'" />'; } } class Field_text Extends Field_standard{ public function getHtmlForm(){ return '<textarea name="'.$this->strName.'">'.$this->getValue().'</textarea>'; } } class FieldFactory{ static public function create($strFieldName, $strFieldType) { $classname="Field_$strType"; if (class_exists($classname, false)) { return new $classname($strFieldName, $strFieldType); }else{ return new CellField_standard($strFieldName, $strFieldType, $strDefaultValue,$strDescription,$boolEditable); } } }//class Friday, June 13. 2008strstr type problem
Well using strstr function i found a variable type handling problem
PHP Version 5.1.2
try
$intSomeID="4";
$strCatList="4,5,6,7";
while
//unexpected behavior
var_dump(strstr($strCatList,$intSomeID)); returns bool(false)
//right behavior
var_dump(strstr($strCatList,"$intSomeID")); returns string "4,5,6,7";
well i always used strstr to string comparsion if something is included inside string and never hat this array before.
Usually you could implode the categorys to an array and use in_array function but it is not needed in that point.
So you have to take care with your variable types using strstr functions.
I wouldn´t call it a bug but something where you have to take care off.
(Page 1 of 2, totaling 18 entries)
» next page
|