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

Doctrine Field Types Reference

Strings

string (used for shorter strings)
text (used for larger strings)
Numbers
integer
smallint
bigint
decimal
float

Dates and Times (use a DateTime object for these fields in PHP)

date
time
datetime

Other Types

boolean
object (serialized and stored in a CLOB field)
array (serialized and stored in a CLOB field)

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 filter SSL

apps/frontend/config/app.yml

  ssl_filter:
    enabled: true
    secure:
      profile:
       actions: ~
      feed:
       actions: ~
      bookmark:
       actions: ~
      alert:
       actions: ~
      sfGuardAuth:
        actions: [signin]
      sfGuardRegister:
        actions: ~
      sfGuardForgotPassword:
        action: ~

lib/filter/sfSslFilter.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
<?php
class sfSslFilter extends sfFilter {
  public function execute($filterChain) {
    if(sfConfig::get('app_ssl_filter_enabled', true) && $this->isFirstCall()) {
      $request = $this->getContext()->getRequest();
      if($request->isMethod('get') || $request->isMethod('head')) {
        $context = $this->getContext();
        $controller = $context->getController();
        $stackEntry = $controller->getActionStack()->getLastEntry();
        $module = $stackEntry->getModuleName();
        $action = $stackEntry->getActionName();
        $moduleSettings = sfConfig::get('app_ssl_filter_secure', false);
        if(isset($moduleSettings[$module])) {
          if(isset($moduleSettings[$module]['actions'])){
            if(!$request->isSecure() && is_array($moduleSettings[$module]['actions']) && in_array($action, $moduleSettings[$module]['actions'])) {
              return $this->redirectSecure($request);
            }
          } else if(!$request->isSecure()) {
            return $this->redirectSecure($request);
          }
        }
      }
    }
    $filterChain->execute();
  }
 
  protected function redirectSecure(sfWebRequest $request) {
    $url = str_replace( 'http', 'https', $request->getUri());
    return $this->getContext()->getController()->redirect($url, 0, 301);
  }
}

apps/frontend/config/filters.yml

ssl:
  class: sfSslFilter

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 minifier le js et css d’un projet symfony simplement

Comment minifier le css et le javascript de son projet symfony

On telecharge yuicompressor chez yahoo yuicompressor

pour des besoin de pure fainéantise, on créé le minify.sh a coter de l’exécutable symfony, on met le .jar de yuicompressor dans le même répertoire ou ailleurs mais il faudra le changer dans le script dans se cas là :)

emacs ou vim minify.sh et on colle ça dedant

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
#!/bin/bash
yui='./yuicompressor-2.4.2.jar' # le path du .jar de yuicompressor
css='./web/css/style.min.css' # le path du css minifier
js='./web/js/be-geek.min.js' # le path du js minifier
 
if [ -f "$css" ]; then
    echo "rm: $css"
    rm $css
fi
 
if [ -f "$css.gz" ]; then
    echo "rm: $css.gz"
    rm $css.gz
fi
 
if [ -f "$js" ]; then
    echo "rm: $js"
    rm $js
fi
 
if [ -f "$js.gz" ]; then
    echo "rm: $js.gz"
    rm $js.gz
fi
 
for i in `ls ./web/css/`
do
    echo $i
    java -jar $yui --type css ./web/css/$i >> $css
done
 
for i in `ls ./web/js/`
do
    echo $i
    java -jar $yui --type js ./web/js/$i >> $js
done
 
echo "gzip $css > $css.gz"
gzip -c -n -3 $css > $css.gz
echo "gzip $js > $js.gz"
gzip -c -n -3 $js > $js.gz
 
echo 'done'

ensuite

bash minify.sh

ce qui nous donne

hio@jupiter:~/www/be-geek.com/trunk$ bash minify
rm: ./web/css/style.min.css
rm: ./web/css/style.min.css.gz
rm: ./web/js/be-geek.min.js
rm: ./web/js/be-geek.min.js.gz
jquery.lightbox-0.5.css
main.css
slides.css
style01.css
jquery.be-geek.js
jquery.lightbox-0.5.min.js
slides.jquery.js
gzip ./web/css/style.min.css > ./web/css/style.min.css.gz
gzip ./web/js/be-geek.min.js > ./web/js/be-geek.min.js.gz
done

et dans le view.yml, on vire les autres .js et .css et on ne met plus que les fichier .js et .css minifier

  stylesheets:    [style.min.css]
  javascripts:    [monjs.min.js]

voila c’était trop dur :)

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, Comment calculer N jours depuis une date

J’ai eu besoin de calculer 92 jour depuis le jour J+1, donc voila, le petit algo mignon.

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
    $month = date('m');
    $year = date('Y');
    $day = date('d', mktime(0, 0, 0, $month, date('d', strtotime("+1 day")), $year));
    $month = date('m', strtotime('+1 day'));
    $dateArray = array();
    $dateArray[] = '';  
    for($i = 0,$j = $day; $i < 92; $i++,$j++) {
      $tmp = array();
      if($j > date('t', mktime(0, 0, 0, $month, '01', $year))) {
        $j = 1;
        if($month == 12) {
          $year = date('Y', mktime(0, 0, 0, '01', '01', $year+1));
        }
        $month = date('m', mktime(0, 0, 0, $month+1, '01', $year));
      }
      if(strlen($j) != 2)
        $tmp[] = '0'.$j;
      else
        $tmp[] = $j;
      if(strlen($month) != 2)
        $tmp[] = '0'.$month;
      else
        $tmp[] = $month;
      $tmp[] = $year;
      $dateArray[] = implode('-', $tmp);
    }

ce qui donne une fois passer a un widget symfony qui va bien

$this->widgetSchema['date_demarage'] = new sfWidgetFormSelect(array('label' => 'Date de démarrage',
                                                                    'choices' => array_combine($dateArray, $dateArray)
                                                                    ));
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<select name="ventes[date_demarage]" id="ventes_date_demarage">
<option value="" selected="selected"></option>
<option value="09-06-2010">09-06-2010</option>
<option value="10-06-2010">10-06-2010</option>
<option value="11-06-2010">11-06-2010</option>
<option value="12-06-2010">12-06-2010</option>
<option value="13-06-2010">13-06-2010</option>
<option value="14-06-2010">14-06-2010</option>
<option value="15-06-2010">15-06-2010</option>
<option value="16-06-2010">16-06-2010</option>
<option value="17-06-2010">17-06-2010</option>
<option value="18-06-2010">18-06-2010</option>
<option value="19-06-2010">19-06-2010</option>
<option value="20-06-2010">20-06-2010</option>
<option value="21-06-2010">21-06-2010</option>
<option value="22-06-2010">22-06-2010</option>
<option value="23-06-2010">23-06-2010</option>
<option value="24-06-2010">24-06-2010</option>
<option value="25-06-2010">25-06-2010</option>
<option value="26-06-2010">26-06-2010</option>
<option value="27-06-2010">27-06-2010</option>
<option value="28-06-2010">28-06-2010</option>
<option value="29-06-2010">29-06-2010</option>
<option value="30-06-2010">30-06-2010</option>
<option value="01-07-2010">01-07-2010</option>
<option value="02-07-2010">02-07-2010</option>
<option value="03-07-2010">03-07-2010</option>
<option value="04-07-2010">04-07-2010</option>
<option value="05-07-2010">05-07-2010</option>
<option value="06-07-2010">06-07-2010</option>
<option value="07-07-2010">07-07-2010</option>
<option value="08-07-2010">08-07-2010</option>
<option value="09-07-2010">09-07-2010</option>
<option value="10-07-2010">10-07-2010</option>
<option value="11-07-2010">11-07-2010</option>
<option value="12-07-2010">12-07-2010</option>
<option value="13-07-2010">13-07-2010</option>
<option value="14-07-2010">14-07-2010</option>
<option value="15-07-2010">15-07-2010</option>
<option value="16-07-2010">16-07-2010</option>
<option value="17-07-2010">17-07-2010</option>
<option value="18-07-2010">18-07-2010</option>
<option value="19-07-2010">19-07-2010</option>
<option value="20-07-2010">20-07-2010</option>
<option value="21-07-2010">21-07-2010</option>
<option value="22-07-2010">22-07-2010</option>
<option value="23-07-2010">23-07-2010</option>
<option value="24-07-2010">24-07-2010</option>
<option value="25-07-2010">25-07-2010</option>
<option value="26-07-2010">26-07-2010</option>
<option value="27-07-2010">27-07-2010</option>
<option value="28-07-2010">28-07-2010</option>
<option value="29-07-2010">29-07-2010</option>
<option value="30-07-2010">30-07-2010</option>
<option value="31-07-2010">31-07-2010</option>
<option value="01-08-2010">01-08-2010</option>
<option value="02-08-2010">02-08-2010</option>
<option value="03-08-2010">03-08-2010</option>
<option value="04-08-2010">04-08-2010</option>
<option value="05-08-2010">05-08-2010</option>
<option value="06-08-2010">06-08-2010</option>
<option value="07-08-2010">07-08-2010</option>
<option value="08-08-2010">08-08-2010</option>
<option value="09-08-2010">09-08-2010</option>
<option value="10-08-2010">10-08-2010</option>
<option value="11-08-2010">11-08-2010</option>
<option value="12-08-2010">12-08-2010</option>
<option value="13-08-2010">13-08-2010</option>
<option value="14-08-2010">14-08-2010</option>
<option value="15-08-2010">15-08-2010</option>
<option value="16-08-2010">16-08-2010</option>
<option value="17-08-2010">17-08-2010</option>
<option value="18-08-2010">18-08-2010</option>
<option value="19-08-2010">19-08-2010</option>
<option value="20-08-2010">20-08-2010</option>
<option value="21-08-2010">21-08-2010</option>
<option value="22-08-2010">22-08-2010</option>
<option value="23-08-2010">23-08-2010</option>
<option value="24-08-2010">24-08-2010</option>
<option value="25-08-2010">25-08-2010</option>
<option value="26-08-2010">26-08-2010</option>
<option value="27-08-2010">27-08-2010</option>
<option value="28-08-2010">28-08-2010</option>
<option value="29-08-2010">29-08-2010</option>
<option value="30-08-2010">30-08-2010</option>
<option value="31-08-2010">31-08-2010</option>
<option value="01-09-2010">01-09-2010</option>
<option value="02-09-2010">02-09-2010</option>
<option value="03-09-2010">03-09-2010</option>
<option value="04-09-2010">04-09-2010</option>
<option value="05-09-2010">05-09-2010</option>
<option value="06-09-2010">06-09-2010</option>
<option value="07-09-2010">07-09-2010</option>
<option value="08-09-2010">08-09-2010</option>
</select>