Snippets tagged "php" Snippets tagged "php"

Hello World !

Hi all, this is just a test :

<?php
abstract class HelloWorld {
  static public function sayIt()
  {
    echo 'Hello World !';
  }
}
 
HelloWorld::sayIt();
?>
by Nicolas Perriault on 2006-10-09, tagged php  test 

Récupérer le nombre d'abonnés feedburner

Pour récupérer le nombre d'abonnés à un flux Feedburner, par exemple celui du flux de prendreuncafe.com :

<?php
$feedName = 'prendreuncafe'; // identifiant feedburner
$xml = @simplexml_load_file(sprintf('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=%s&dates=%s,%s',
  $feedName,
  date('Y-m-d', strtotime('-2 day')),
  date('Y-m-d', strtotime('-1 day'))));
if (!$xml) throw new RuntimeException('Feed unavailable');
var_dump((int) $xml->feed->entry[0]['circulation']);

Source d'inspiration : Oncle Tom

by Nicolas Perriault on 2009-05-14, tagged api  feedburner  php 

Autocomplétion au sein d'eclipse

Copier-coller le code suivant dans un fichier xml :

<?xml version="1.0" encoding="UTF-8" standalone="no"?><templates><template autoinsert="true" context="php" deleted="false" description="create a Symfony Action" enabled="true" name="action">public function execute${Action} {
  ${body}
}</template><template autoinsert="true" context="php" deleted="false" description="Create a class controller" enabled="true" name="controller">class ${ControllerName}Actions extends sfActions  {
 
    public  function execute${action}()
 
    {
      ${body}
    }
 
}
</template><template autoinsert="true" context="php" deleted="false" description="criteria doSelect" enabled="true" name="doselect">$$c = new Criteria;
$$${objects} = ${propelObject}Peer::doSelect($$c);</template></templates>

Installation au sein d'eclipse

  • Dans eclipse allez dans Window > Preferences
  • Choisir PHP dans la liste des préférences
  • Choisir Template et cliquer sur Import
  • Selectionner le fichier xml puis accepter

Note: Le mieux serait de s'inspirer des templates de texmate afin de se monter un système de templating complet pour Eclipse. Ajout également de commentaires compatibles phpdocumentor

by Samuel MARTIN on 2008-07-22, tagged autocompletion  completion  eclipse  php  snippet  symfony  template 

[Symfony] Effacer partiellement le cache d'une application

Toujours utile depuis un contexte d'application différent de celui visé :

sfToolkit::clearGlob(sfConfig::get('sf_cache_dir').'/frontend/*/all/*/templates/toto.cache');
by Nicolas Perriault on 2008-05-26, tagged cache  php  symfony 

Passer outre le "allow_url_fopen et allow_url_include" a Off

Qui n'a jamais eu un Warning de type : "filegetcontents() function.file-get-contents: URL file-access is disabled in the server configuration in % on line %" sur un hebergement mutualisé ?

la solution et d'utiliser lynx en ligne de commande pour attaquer une url, on utilisera la fonction exec(), exemple avec l'api GoogleMaps

<?php
 
define('GOOGLE_API_KEY', 'your_google_api_key_here');
$wsurl = 'http://maps.google.com/maps/geo?q=%s&output=csv&key=%s';
$location = 'Paris, France';
 
$data = explode(',', exec('lynx --dump \''.sprintf($wsurl, urlencode($location), GOOGLE_API_KEY).'\''));
/*** Au lieu de ***/
$data = explode(',', file_get_contents(sprintf($wsurl, urlencode($location), GOOGLE_API_KEY)));
 
 
$coord = 200 === (int)$data[0] ? array((float)$data[2], (float)$data[3]) : null;
var_dump($coord);
?>
by EL BROUDI ALI on 2008-05-13, tagged allowurlfopen  filegetcontents  googlemap  php 

[Symfony] Un validateur de date qu'il est bien

Quelques fonctionnalités en plus par rapport à sfDateValidator (qu'il étend), notamment l'interdiction de date futures ou passées et l'évitement du traitement de la langue courante utilisateur (utile pour les formats de date figés).

/**
 * Custom date validator
 *
 */
class myDateValidator extends sfDateValidator
{
  /**
   * Execute this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
  public function execute(&$value, &$error)
  {
    $culture = $this->getContext()->getUser()->getCulture();
 
    // Validate the given date
    if ($this->getParameter('with_culture'))
    {
      $value1 = $this->getValidDate($value, $culture);
    }
    else
    {
      $value1 = strtotime($value);
    }
 
    if (!$value1 || -1 == $value1) // Before php 5.1, strtotime() returns -1 on fail
    {
      $error = $this->getParameter('date_error');
      return false;
    }
 
    // Is there a compare to do?
    $compareDateParam = $this->getParameter('compare');
    $compareDate = $this->getContext()->getRequest()->getParameter($compareDateParam);
 
    // If the compare date is given
    if ($compareDate)
    {
      $operator = trim($this->getParameter('operator', '=='), '\'" ');
      $value2 = $this->getValidDate($compareDate, $culture);
 
      // If the check date is valid, compare it. Otherwise ignore the comparison
      if ($value2)
      {
        $valid = false;
        switch ($operator)
        {
          case '>':
            $valid = $value1 >  $value2;
            break;
          case '>=':
            $valid = $value1 >= $value2;
            break;
          case '==':
            $valid = $value1 == $value2;
            break;
          case '<=':
            $valid = $value1 <= $value2;
            break;
          case '<':
            $valid = $value1 <  $value2;
            break;
 
          default:
            throw new sfValidatorException(sprintf('Invalid date comparison operator "%s"', $operator));
        }
 
        if (!$valid)
        {
          $error = $this->getParameter('compare_error');
 
          return false;
        }
      }
    }
 
    if (!$this->getParameter('allow_future') && $value1 > time())
    {
      $error = $this->getParameter('future_error');
      return false;
    }
 
    if (!$this->getParameter('allow_past') && $value1 < time())
    {
      $error = $this->getParameter('past_error');
      return false;
    }
 
    return true;
  }
 
  /**
   * Initializes the validator.
   *
   * @param sfContext The current application context
   * @param array   An associative array of initialization parameters
   *
   * @return bool true, if initialization completes successfully, otherwise false
   */
  public function initialize($context, $parameters = null)
  {
    // Initialize parent
    parent::initialize($context, $parameters);
 
    // Set defaults
    $this->getParameterHolder()->set('with_culture', true);
    $this->getParameterHolder()->set('allow_future', true);
    $this->getParameterHolder()->set('future_error', 'Future dates not allowed');
    $this->getParameterHolder()->set('allow_past', true);
    $this->getParameterHolder()->set('past_error', 'Past dates not allowed');
    $this->getParameterHolder()->add($parameters);
 
    return true;
  }
}
by Nicolas Perriault on 2008-03-16, tagged date  php  symfony  validator 

Compiler tous les fichiers PHP en un seul

Pour faire un gros fichier comportant l'intégralité d'un projet par exemple :

$ find . -name "*.php" |xargs php -w > mongrosprojet.php
by Nicolas Perriault on 2008-03-15, tagged php 

Formatter un document XML avec DOM et PHP5

Ça peut bien aider.

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->load('/path/to/file.xml');
$dom->formatOutput = true;
file_put_contents('formatted.xml', $dom->saveXML());
by Nicolas Perriault on 2007-04-16, tagged dom  format  php  php5  tidy  xml 

[Symfony] Chemins systèmes

Voici les chemins systèmes par défaut dans Symfony.

// root directory structure
'sf_cache_dir_name'   => 'cache',
'sf_log_dir_name'     => 'log',
'sf_lib_dir_name'     => 'lib',
'sf_model_dir_name'   => 'model',
'sf_web_dir_name'     => 'web',
'sf_data_dir_name'    => 'data',
'sf_config_dir_name'  => 'config',
'sf_apps_dir_name'    => 'apps',
 
// global directory structure
'sf_app_dir'        => $sf_root_dir.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$sf_app,
'sf_model_dir'      => $sf_root_dir.DIRECTORY_SEPARATOR.'model',
'sf_lib_dir'        => $sf_root_dir.DIRECTORY_SEPARATOR.'lib',
'sf_web_dir'        => $sf_root_dir.DIRECTORY_SEPARATOR.'web',
'sf_upload_dir'     => $sf_root_dir.DIRECTORY_SEPARATOR.'web'.DIRECTORY_SEPARATOR.'uploads',
'sf_base_cache_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.$sf_app,
'sf_cache_dir'      => $sf_root_dir.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.$sf_app.DIRECTORY_SEPARATOR.$sf_environment,
'sf_log_dir'        => $sf_root_dir.DIRECTORY_SEPARATOR.'log',
'sf_data_dir'       => $sf_root_dir.DIRECTORY_SEPARATOR.'data',
'sf_config_dir'     => $sf_root_dir.DIRECTORY_SEPARATOR.'config',
by Nicolas Perriault on 2007-01-29, tagged filesystem  php  symfony 

[Symfony] Autoloader toutes les classes d'un répertoire particulier

Il est très simple de charger automatiquement toutes les classes PHP définies dans un répertoire avec Symfony :

require_once($sf_symfony_lib_dir.'/util/sfCore.class.php');
sfCore::initSimpleAutoload('/path/to/libs');
by Nicolas Perriault on 2007-01-17, tagged autoload  php  symfony 

Réduire le coût de performances de require_once

La fonction require_once étant assez coûteuse en PHP, il peut être intéressant de tester l'existence de l'objet que le fichier définit avant de le charger d'emblée :

class_exists('sfCache') or require_once($sf_symfony_lib_dir.'/cache/sfCache.class.php');
by Nicolas Perriault on 2007-01-15, tagged optimisation  performance  php 
(2 comments)

[Symfony] Traiter les OR sql avec Propel

Voici comment gérer les "ou" SQL dans Propel :

$criteria = new Criteria();
$criteria->add(TotoPeer::NAME, 'Gérard Bouchard');
$criterion = $criteria->getNewCriterion (
  TotoPeer::ID, 5
)->addOr($criteria->getNewCriterion (
  TotoPeer::ID, 10
));
$criteria->addAnd($criterion);
TotoPeer::doSelect($criteria);

Ceci donnera quelque chose comme :

SELECT 
  * 
FROM 
  toto 
WHERE 
  toto.NAME = 'Gérard Bouchard' 
  AND 
  (
    toto.ID = 5 
    OR 
    toto.ID = 10
  );
by Nicolas Perriault on 2007-01-15, tagged mysql  php  propel  sql  symfony 

Générer la PHPDoc d'un projet

$ sudo apt-get install php-pear
$ sudo pear install PhpDocumentor
$ phpdoc -d /path/to/project/sources -t /path/to/project/doc
by Nicolas Perriault on 2006-12-26, tagged pear  php  phpdoc  ubuntu 

Multiton en PHP5

class Multiton
{
  private $instances = array();
 
  public function getInstance($var1, $var2, $var3)
  {
    $uid = md5((string)$var1.(string)$var2.(string)$var3);
    if (!isset(self::$instances[$uid])) 
    { 
      self::$instances[$uid] = new Multiton($var1, $var2, $var3);
    }
    return self::$instances[$uid];
  }
 
}
by Nicolas Perriault on 2006-12-26, tagged pattern  php 

Récupérer la taille d'une vidéo en PHP avec ffmpeg

On a besoin de http://ffmpeg-php.sourceforge.net/, puis :

extension_loaded('ffmpeg') or die('ffmpeg extension not loaded');
 
$ffmpegInstance = new ffmpeg_movie('/path/to/movie.avi');
$ffmpegInstance->getDuration(); // Gets the duration in secs.
$ffmpegInstance->getVideoCodec(); // What type of compression/codec used
by Nicolas Perriault on 2006-12-21, tagged audio  ffmpeg  php  video 

Foreach et les variables passées en référence

Merci Thibs ;)

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) 
{
  $value = $value * 2;
}
print_r($arr); // $arr vaut maintenant array (2, 4, 6, 8)
by Nicolas Perriault on 2006-11-23, tagged array  foreach  php  reference 

[Symfony] Utiliser un helper dans une action

sfLoader::loadHelpers(array('First', 'Second'));

Simple !

by Nicolas Perriault on 2006-11-23, tagged helper  php  symfony 

Le pattern Strategy en PHP5

<?php
interface IStrategy
{
  function filter( $record );
}
 
class FindAfterStrategy implements IStrategy
{
  private $_name;
 
  public function __construct( $name )
  {
    $this->_name = $name;
  }
 
  public function filter( $record )
  {
    return strcmp( $this->_name, $record ) <= 0;
  }
}
 
class RandomStrategy implements IStrategy
{
  public function filter( $record )
  {
    return rand( 0, 1 ) >= 0.5;
  }
}
 
class UserList
{
  private $_list = array();
 
  public function __construct( $names )
  {
    if ( $names != null )
    {
      foreach( $names as $name )
      {
        $this->_list []= $name;
      }
    }
  }
 
  public function add( $name )
  {
    $this->_list []= $name;
  }
 
  public function find( $filter )
  {
    $recs = array();
    foreach( $this->_list as $user )
    {
      if ( $filter->filter( $user ) )
        $recs []= $user;
    }
    return $recs;
  }
}
 
$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );
$f1 = $ul->find( new FindAfterStrategy( "J" ) );
print_r( $f1 );
 
$f2 = $ul->find( new RandomStrategy() );
print_r( $f2 );
?>
by Nicolas Perriault on 2006-11-07, tagged pattern  php 

Le pattern ChainOfCommands en PHP5

<?php
interface ICommand
{
  function onCommand( $name, $args );
}
 
class CommandChain
{
  private $_commands = array();
 
  public function addCommand( $cmd )
  {
    $this->_commands []= $cmd;
  }
 
  public function runCommand( $name, $args )
  {
    foreach( $this->_commands as $cmd )
    {
      if ( $cmd->onCommand( $name, $args ) )
        return;
    }
  }
}
 
class UserCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'addUser' ) return false;
    echo( "UserCommand handling 'addUser'\n" );
    return true;
  }
}
 
class MailCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'mail' ) return false;
    echo( "MailCommand handling 'mail'\n" );
    return true;
  }
}
 
$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( 'addUser', null );
$cc->runCommand( 'mail', null );
?>
by Nicolas Perriault on 2006-11-07, tagged pattern  php 

Le pattern Observer en PHP5

<?php
interface IObserver
{
  function onChanged( $sender, $args );
}
 
interface IObservable
{
  function addObserver( $observer );
}
 
class UserList implements IObservable
{
  private $_observers = array();
 
  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }
 
  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}
 
class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}
 
$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>
by Nicolas Perriault on 2006-11-07, tagged pattern  php 

Le pattern Factory en PHP5

<?php
interface IUser
{
  function getName();
}
 
class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }
 
  public static function Create( ) 
  {
        return new User( null );
  }
 
  public function __construct( $id ) { }
 
  public function getName()
  {
    return "Jack";
  }
}
 
$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>
by Nicolas Perriault on 2006-11-07, tagged pattern  php 

Singleton en PHP5

Instance unique d'un objet.

<?php 
class Singleton 
{ 
    private static $_instance ; 
 
    private function __construct() { }
 
    public static function GetInstance() 
    { 
        if (!isset(self::$_instance)) 
        { 
            self::$_instance = new Singleton() ; 
        } 
        return self::$_instance; 
    }
}
?>
by Nicolas Perriault on 2006-10-11, tagged design  pattern  php  singleton 

Obtenir un tableau de caractères depuis une chaîne en PHP4

En php5 on a str_split : http://fr.php.net/manual/fr/function.str-split.php

Et en PHP4 :

$chars = preg_split('#(?<=.)(?=.)#s', $string);
by Nicolas Perriault on 2006-10-11, tagged array  php  string 
(3 comments)