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. 2010Remove Duplicated Entries from MySQL Table
This is a short tutorial how to remove duplicated entries from MySQL DB Table
First idea was just to do a simple DELETE statement on a SubSelect
DELETE FROM user WHERE id IN (SELECT u2.id FROM user AS u1 JOIN user AS u2 ON u1.name=u2.name WHERE u1.id < u2.id) Error 1093 (ER_UPDATE_TABLE_USED) SQLSTATE = HY000 Message = "You can't specify target table 'x' for update in FROM clause" This error occurs in cases such as the following: UPDATE t1 SET column2 = (SELECT MAX(column1) FROM t1); You can use a subquery for assignment within an UPDATE statement because subqueries are legal in UPDATE and DELETE statements as well as in SELECT statements. However, you cannot use the same table (in this case, table t1) for both the subquery's FROM clause and the update target.I was searching for a solution without using temporary table but didn´t find one yet. CREATE TEMPORARY TABLE duplicated_temp(id INT) TYPE=HEAP; INSERT INTO duplicated_temp SELECT u2.id FROM ex_user AS u1 JOIN user AS u2 ON u1.name=u2.name WHERE u1.id < u2.id; DELETE FROM user WHERE id IN (SELECT id FROM duplicated_temp WHERE 1); DROP TABLE duplicated_temp; Dynamic 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; } } Tuesday, December 29. 2009Osapi Session Storage
Using the OSAPI Open Social API, i noticed there is no session storage available by default,
so this is a very quick way to implement a PHP-Session Bages Storage
// Session Storage implements Openid Storage Inside PHP Session, //for me the easiest way to handle openId data // // Description of osapiSessionStorage // //@author John Behrens (john.behrens@webconsults.eu) // class osapiSessionStorage extends osapiStorage{ // // Retrieves the data for the given key, or false if they // key is unknown or expired // // @param String $key The key who's data to retrieve // @param int $expiration Experiration time in seconds // public function get($key, $expiration = false){ if(!isset($_SESSION['osapi'])){ return false; } if(isset($_SESSION['osapi'][$key])){ return $_SESSION['osapi'][$key]; }else{ return false; } } // //Store the key => $value set. The $value is serialized // by this function so can be of any type // //@param String $key Key of the data // @param Any-type $value the data // public function set($key, $value){ $_SESSION['osapi'][$key]=$value; } // // Removes the key/data pair for the given $key // // @param String $key // public function delete($key){ unset($_SESSION['osapi'][$key]); } } ?> Thursday, October 22. 2009One more reason why Symfony **cks
I was working with
form_remote_tag() which is a usefull function if you create forms using AJAX request.
Simple usage is easy
Executes the URL Item Add and replaces content of the Element with item_list with it´s result.
Well what i would like to now is a Form which is permanent viewable and will reset itself if sended.
What i guessed
<?php echo form_remote_tag(array( 'update' => 'list', 'url' => 'entrys/create', 'complete' => "Form.reset('myForm')", 'id'=>'myForm' )); ?> <?php echo form_remote_tag(array( 'update' => 'list', 'url' => 'rntrys/create', 'complete' => "Form.reset('myForm')" ),"id='myForm' "); ?> Monday, October 12. 2009Tooltip Div with Jquery
Searching the web i found a lot of solutions and ToolTip Plugins wie z.b. Simpletip oder really simple tooltop, but after i had a short look at some i decided that they are all more or less usefull.
The most usuable entry i found was a short entry at Stackoverflow telling me anything i need to know.
My basic requirement was, Javascript code has to be Seperated from the design and the Webpage content.
So my php template looks like this
<? foreach($entrys as $entry): ?> <div id="entrylink_<?=$entry->id?>"> <a href="<?=$entry->link?>" onMouseOver="showEntryPreview('<?=$entry->id?>')" onMouseOut="hideEntryPreview('<?=$entry->id?>')"><?=$entry->name?></a> </div> <div id="entryinfo_<?=$entry->id?>" class="entry_preview"> ... some more information .... </div> <?enforeach;?> .entry_preview{ position:absolute; z-index:999; left:-9999px; background-color:#FF0000; padding:5px; border:1px solid #fff; width:250px; function showUserInfo(entryId){ var divOverlay=$('#entrylink_'+entryId); var divParent=$('#entryinfo_'+entryId); var parentPosition=divParent.position(); var parentWidth=divParent.width(); var parentHeight=divParent.height(); divOverlay.css('left', parentPosition.left+parentWidth); divOverlay.css('top', parentPosition.top+parentHeight); divOverlay.css('visibility', 'visible'); } function hideUserInfo(entryId){ $('#entryinfo_'+userId).css('visibility', 'hidden'); } 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, July 30. 2009Internationalization in User Generated Enviorments
User generated content in multilingual enviorments brings up new internationalizations problems,
in a social network or other enviorment with a lot of User Generated content, I18N could not be sticked strictly to the user, and even a content or discussion could be spreaden through different languages.
On usual websites a language is assigned to the frontend user, also on Youtube where it causes some problems.
I always recieve Mails like
Komentarze do filmu „>videoname<” Comentario sobre ">videoname<" publicado Reactie van >userwhopostedcomment< op ,>videoname<' Nouveau commentaire sur ">videoname<" Kommentar zu ">videoname<" gepostet" gepostetWhich all mean your video ... has been commented by ..., but it´s alsways in the default language to the commentor, no matter what my language is and no matter which language the comment is Written in. Comments itself are mostly written in english or the language the video is in. A solution could be to send it just in the recipient´s default language instead the actual frontend language, it would just make it easier for the recipient. Jeroen - Moie Video, echt Leuk Tommy - Why are all the Comments in Dutch Franz - Die Holländer finden ihre Sprache so Toll Antje - Ihre Sprache ist auch Supertoll Joost - Duits is alleen voor Moffen Tommy - In English Please Joost - German is for Kauts Only Franz - Geh doch Käse essen du KaaskoppAs you see users could communicate through different Languages, and maybe they even like it and switch Languages during a conversation, if you wanna run your site with an international flavour this is acceptable. Language Detection Language Detection could be usefull, to translate auto detection for example, but you could also hide content with Language Detection For Example: I got a Guestbook entry on my Dutch Netlog, somebody commentet the guestbook in German with something like "Hi ich habe ein bischen Deutsch gelernt, Wie geht es dir? viele grüsse". This entry were hidden cause it weren´t written in my actual frontend Language (Dutch), but actually i had choosen German as native language in my profile. So if you use something like Language Detection to hide content from foreign Languages, you must consider a user could be able to understand more than one language. Hiding content from the user is mostly a bad decission, cause even if the user is not able to read information might be usefull. The better way is always to sign the entry as an entry with different language and offer automated translation possibility. Where it could make sense to hide content is if a user is doing a general search on contents, at least in order of the search results. Friday, June 26. 2009Zend Debug Logger
http://extraordinaire.me/web-development/bootstrap-zend-framework/
Wednesday, May 6. 2009Eclipse Visual Editor vs Netbeans GUI Designer
Some days ago i started my first Java project including a GUI,
first i began with using eclipse and the beginning was fine, until i came to that point were i had to create the GUI Interface.
I didn´t had the intension to define my GUI in writing lines of code, i was mostly searching for something to design a GUI by moving arround some buttons and editor boxes like in Visual Studio or Delphi.
After a few tryouts with outdated tutorials i could finally install the Visial Editor for Eclipse by using this tutorial, i noticed that comfortable solution i am searching for, searching arround how to work with it i just found out, the VE is propably not able to do what i tried.
So i decided to try out Netbeans, and i were completly satisfied, download and installation were quite easy and the GUI Designer does it´s work almost perfectly, you don´t have to waste your time in configurating layouts just move them arround with drag and drop, almost as good as in Delphi.
So what i decided was stop to use Eclipse for that Java stuff and start to use Netbeans and so far Netbeans hits all of my needs exactly, even seems to be more out of one piece than eclipse.
Maybe gonna try it out Netbeans for PHP aswell.
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";
(Page 1 of 3, totaling 37 entries)
» next page
|