doctrine2 yaml mapping example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Doctrine\Tests\ORM\Mapping\User:
  type: entity
  table: cms_users
  namedQueries:
    all: SELECT u FROM __CLASS__ u
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
      sequenceGenerator:
        sequenceName: tablename_seq
        allocationSize: 100
        initialValue: 1
  fields:
    name:
      type: string
      length: 50
      nullable: true
      unique: true
    email:
      type: string
      column: user_email
      columnDefinition: CHAR(32) NOT NULL
  oneToOne:
    address:
      targetEntity: Address
      inversedBy: user
      joinColumn:
        name: address_id
        referencedColumnName: id
        onDelete: CASCADE
        onUpdate: CASCADE
      cascade: [ remove ]
  oneToMany:
    phonenumbers:
      targetEntity: Phonenumber
      orphanRemoval: true
      mappedBy: user
      orderBy:
        number: ASC
      cascade: [ persist ]
  manyToMany:
    groups:
      targetEntity: Group
      joinTable:
        name: cms_users_groups
        joinColumns:
          user_id:
            referencedColumnName: id
            nullable: false
            unique: false
        inverseJoinColumns:
          group_id:
            referencedColumnName: id
            columnDefinition: INT NULL
      cascade:
        - all
  lifecycleCallbacks:
    prePersist: [ doStuffOnPrePersist, doOtherStuffOnPrePersistToo ]
    postPersist: [ doStuffOnPostPersist ]
  uniqueConstraints:
    search_idx:
      columns: name,user_email
  indexes:
    name_idx:
      columns: name
    0:
      columns: user_email

Symfony2 memo

php app/console generate:bundle --namespace=Gallery/AlbumBundle --format=yml
 
php app/console doctrine:database:create
 
php app/console doctrine:generate:entity --entity="GalleryAlbumBundle:Album" --fields="name:string(255) description:text"
 
php app/console doctrine:generate:entities Gallery
php app/console doctrine:generate:entities GalleryAlbumBundle
php app/console doctrine:generate:entities Gallery/AlbumBundle/Entity/Album
 
php app/console doctrine:schema:update --force

Symfony comment délivrer son contenu static a partir de plusieurs cdn

On crée ce fichier dans le répertoire lib/ ou a l’endroit ou on veut du moment que l autoloader de sf peut le trouver, perso je l’ai mit dans lib/vendor/hio/
sfStatics.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
class sfStatics {
  static public $statics;
  static public $number;
  static public $index = 0;
  private static $instance = null;
 
  public static function getInstance($statics) {
    if(is_null(self::$instance))
      self::$instance = new sfStatics($statics);
 
    return self::$instance;
  }
 
  public function __construct($statics) {
    self::$statics = $statics;
    self::$number = sizeof($statics)-1;
  }
 
  public function pickOne($n = null) {
    if(is_null($n)) {
      if(self::$index > self::$number)
        self::$index = 0;
 
      $static = self::$statics[self::$index];
      self::$index++;
    } else {
      if(isset(self::$statics[$n])) {
        $static = self::$statics[$n];
      } else {
        $static = self::$statics[0];
      }
    }
    return $static;
  }
 
  public function __toString() {
    return $this->pickOne();
  }
 
}

ensuite on crée un helper qui va bien
mkdir /lib/helper a la racine de son projet (là ou se trouve ./symfony)

StaticHelper.php

<?php
function pickOneStatic($n = null) {
  $a = sfStatics::getInstance(sfConfig::get('app_static_urls'));
  return $a->pickOne($n);
}

on met la liste de ses cdn dans app.yml (apps/frontend/config/app.yml)

# default values
all:
  static:
    urls: ['http://static1.gik.li', 'http://static2.gik.li', 'http://static3.gik.li', 'http://static4.gik.li']

ensuite on passe au chose serieuse dans ses templates

<link rel="shortcut icon" href="<?php echo pickOneStatic(0)?>/images/favicon.ico" />
<link rel="stylesheet" type="text/css" media="screen" href="<?php echo pickOneStatic(0)?>/css/style.min.css" />

dans ses 2 exemples on voit un 0 en argument (0 = le premier cdn de la liste du app.yml), c’est pour délivrer ce contenu tjs a partir du même cdn par exemple qd vous avez plusieurs fois la même images dans une page ou pour que les fichiers js soit cacher correctement par le navigateur

2 eme exemple:

<?php foreach($images as $image): ?>
<?php if(file_exists(sfConfig::get('sf_web_dir').$image->getPath().sfConfig::get('app_images_thumbs_dir').$image->getName())): ?>
<a href="<?php echo url_for('@show?slug='.$image->getContent()->getSlug()) ?>" title="<?php echo $image->getContent()->getTitle() ?>">
    <img src="<strong><?php echo pickOneStatic()?></strong><?php echo $image->getPath().sfConfig::get('app_images_thumbs_dir').$image->getName() ?>" width="60" height="60" alt="<?php echo $image->getName() ?>"/>
</a>
<?php endif ?>
<?php endforeach ?>

donnera

<a href="/gran-turismo-5-suzuka-sous-la-pluie-en-video-la-claque-tout-simplement-1" title="Gran Turismo 5 : Suzuka sous la pluie en vidéo - La claque, tout simplement"> 
    <img src="http://static1.gik.li/img/2010-11-21/thumbs/051cb8a3476f3fe29ee4975ec32d217c72fb7593.jpg" width="60" height="60" alt="051cb8a3476f3fe29ee4975ec32d217c72fb7593.jpg"/> 
</a> 
<a href="/jolibook-now-on-sale-in-the-uk-first-batch-of-orders-ships-monday" title="Jolibook now on sale in the UK, first batch of orders ships Monday"> 
    <img src="http://static2.gik.li/img/2010-11-21/thumbs/067c639cac46fa7fe93748a9de23504c1ede1701.jpg" width="60" height="60" alt="067c639cac46fa7fe93748a9de23504c1ede1701.jpg"/> 
</a> 
<a href="/ea-sports-on-nba-elite-it-was-just-going-to-be-a-bad-game-nba-elite" title="EA Sports On NBA Elite: &quot;It Was Just Going To Be A Bad Game&quot; [Nba Elite]"> 
    <img src="http://static3.gik.li/img/2010-11-21/thumbs/524068c6bd9e5f1ffd40311f843cdbac8acfbfb8.jpg" width="60" height="60" alt="524068c6bd9e5f1ffd40311f843cdbac8acfbfb8.jpg"/> 
</a> 
<a href="/bellemanie-bellemanie-2010-watercolor-ink-drawing" title="bellemanie:
 
Bellemanie - (2010, Watercolor &amp; ink drawing)"> 
    <img src="http://static4.gik.li/img/2010-11-21/thumbs/58c5c1637ea9f1193fc4415ff3e1dc5e2ac77d40.jpg" width="60" height="60" alt="58c5c1637ea9f1193fc4415ff3e1dc5e2ac77d40.jpg"/> 
</a> 
<a href="/laterality-in-canine-cradling-madscience" title="Laterality in canine cradling [Madscience]"> 
    <img src="http://static1.gik.li/img/2010-11-21/thumbs/feb4a03be8a2a201eac3cdd0cfe8d6fb5e00e624.jpg" width="60" height="60" alt="feb4a03be8a2a201eac3cdd0cfe8d6fb5e00e624.jpg"/> 
</a>

et ainsi de suite a chaque appel de la fonction sans argument ça passera au prochain cdn

Comment importer un csv dans une database mysql

voila comment importer un csv de plusieurs milliers de lignes dans une database mysql, niveau perf, 30 000 lignes, sont inserer en a peut prêt 4 sec sur ma machine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
error_reporting(E_ALL);
class code extends PDO {
  const FETCH_MODE = PDO::FETCH_ASSOC;
 
  public function __construct($dsn, $username, $password) {
    try {
      return parent::__construct($dsn,
                                 $username,
                                 $password,
                                 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
 
  public function import($csv) {
    try {
      $insert = 0;
      $i = 0;
      $transac = 1000;
      if(!file_exists($csv))
        throw new Exception($csv.' not exists');
      $sth = $this->prepare('INSERT INTO `cheque` SET `code` = :code');
      if(($handle = fopen($csv, 'r')) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
          if($i == 0) {
            echo 'transaction start.'.PHP_EOL;
            $this->beginTransaction();
          }
          $sth->bindValue(':code', $data[1], PDO::PARAM_STR);
          if(!$sth->execute()) {
            $this->rollBack();
            $error = $sth->errorInfo();
            throw new Exception($error[2]);
          }
          $insert++;
          $i++;
          if($i == $transac) {
            echo 'transaction commit: '.$i.' row.'.PHP_EOL;
            $this->commit();
            $i = 0;
          }
        }
        fclose($handle);
      }
    } catch (Exception $e) {
      echo $e->getMessage();
    }
    return $insert;
  }
}
 
/* CONFIGURATION */
$dsn = 'mysql:dbname=database;host=localhost';
$username = 'username';
$password = 'password';
$csv = 'cheque_2010.csv';
/* DO NOT CROSS THE LINE !! */
 
$code = new code($dsn, $username, $password);
echo $code->import($csv);
?>

PHP Symfony, Comment définir un groupe avec sfGuardDoctrinePlugin lors d’une inscription

Tout est dans le titre

protected function processForm(sfWebRequest $request, sfForm $form)
{
  $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
  if($form->isValid())
  {
    $register = $form->save();
    $register->addGroupByName('member');
    $register->addPermissionByName('member');
    $register->profile->setSfGuardUserId($register->id);
    $register->save();
    $this->getUser()->signIn($this->form->getObject());
    $this->redirect('@feeds');
  }
  $this->getUser()->setFlash('error','formular is not correctly filled.');
}

PHP Symfony, Comment passer une valeur a un objet sfForm dans le backend d’une application

apps/backend/modules/hosts/actions/actions.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class hostsActions extends autoHostsActions
{
 
  public function executeCreate(sfWebRequest $request)
  {
    $this->form = $this->configuration->getForm();
    $this->hosts = $this->form->getObject();
 
    $tainted_values = $request->getParameter($this->form->getName());     
    $tainted_values['user_id'] = $this->getUser()->getGuardUser()->getId();
 
    $request->setParameter($this->form->getName(), $tainted_values);
    parent::processForm($request, $this->form);
    $this->setTemplate('new');
  }
}

PHP session avec memcached

Comment stocker les session php dans un memcached en 1 minute chrono

GO !

Installation de memcached

aptitude install memcached
aptitude install php5-memcache

modifier la conf dans /etc/memcached.conf au besoin (augmenter la memoire utiliser, etc…)

et ensuite dans le php.ini qui devrai se trouver ici /etc/php5/apache2/php.ini

session.save_handler = memcache
session.save_path="tcp://127.0.0.1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

On restart apache

/etc/init.d/apache2 restart

un petit script php pour voir se qu’il se passe
http://livebookmark.net/journal/2008/05/21/memcachephp-stats-like-apcphp/