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

playlist.py

#!/usr/bin/python
# -*- coding: utf-8 -*- 
import os
import mimetypes
import string
import sys
import shutil
import getopt
import re
 
class main:
 
    def usage(self):
        print('%s %s dir te explore'%('-i', '--indir'))
        print('%s %s playlist output'%('-p', '--playlist'))
        print('exemple: %s %s %s'%(__file__, '--indir=/var/www/mp3', '-p ./blu.xml'))
 
    def __init__(self, argv):
        self.indir = 0
        self.playlist = 'playlist.xml'
        try:
            opts, args = getopt.getopt(argv, "i:p", ["indir=", "playlist="])
        except getopt.GetoptError:
            self.usage()
            sys.exit(2)
 
        for opt, arg in opts:
            if opt in ('-i', '--indir'):
                if(os.path.exists(arg) == 0):
                    sys.exit(1)
                print('walk %s'%(arg))
                self.indir = arg
            elif opt in ('-p', '--playlist'):
                print('playlist %s'%(arg))
                self.playlist = arg
 
        if self.indir != 0:
            self.run()
        else:
            self.usage()
 
    def strReplace(self, str, array):
        for search, replace in array:
            str = str.replace(search, replace)
        return str
 
    def _human_key(self, key):
        parts = re.split('(\d*\.\d+|\d+)', key)
        return tuple((e.swapcase() if i % 2 == 0 else float(e))
                     for i, e in enumerate(parts))
 
    def run(self):
        print 'run'
        xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
        xml += '<playlist version="1" xmlns="http://xspf.org/ns/0/">\n'
        xml += '<title>'+os.path.split(self.playlist)[1].replace('_', ' ').replace('.xml', '')+'</title>\n'
        xml += '<creator>Bayard</creator>\n'
        xml += '<link></link>\n'
        xml += '<info></info>\n'
        xml += '<image></image>\n'
        xml += '<trackList>\n'
        for dirpath, dirnames, filenames in os.walk(self.indir):
            c = os.path.split(dirpath)[1]
            filenames.sort(key=self._human_key)
            for filename in filenames:
                print dirpath+'/'+filename
                newfilename = self.strReplace(filename, [(' ', '_'), ('–', '-')]);
                fo_path = os.path.join(dirpath, filename)
                fn_path = os.path.join(dirpath, newfilename)
                f_mime = mimetypes.guess_type(fo_path)
                if(os.path.exists(fn_path) == 0):
                    print('%s move to %s'%(fo_path, fn_path))
                    shutil.move(fo_path, fn_path)      
                if f_mime[0] == 'audio/mpeg':
                    xml += '  <track>\n'
                    xml += '    <title>'+newfilename.replace('_', ' ').replace('.mp3', '')+'</title>\n';
                    xml += '    <location>http://bayardmusique.bayardcdn.com/'+c+'/'+filename+'</location>\n';
                    xml += '  </track>\n'
        xml += '</trackList>\n'
        xml += '</playlist>'
        self.write(xml)
 
    def write(self, xml):
        print('write %s'%(self.playlist))
        f = open(self.playlist, 'w')
        f.write(xml)
        f.close()
 
 
if __name__ == "__main__":
    main(sys.argv[1:])

wwwperm.sh

#!/bin/bash
www=$2
dirperms="750"
fileperms="640"
owner="www-data:www-data"
 
function usage {
    echo "Usage:"
    echo "$0 --all /home/www"
    echo "$0 --dir /home/www"
    echo "$0 --file /home/www"
    echo "$0 --owner /home/www"
}
 
if [[ $1 == "" || $2 == "" ]]; then
    usage
    exit 1
fi
 
case $1 in
    '--all')
        bash $0 --dir $www
        bash $0 --file $www
        bash $0 --owner $www
        ;;
    '--dir')
        echo "fixing dirs in $www ..."
        find $www -type d -exec sh -c "chmod $dirperms '{}'" \;
        ;;
    '--file')
        echo "fixing files in $www ..."
        find $www -type f -exec sh -c "chmod $fileperms '{}'" \;
        ;;
    '--owner')
        echo "fixing owner in $www ..."
        chown -R $owner $www
        ;;
    *)
        usage
        exit 1
esac
 
exit 0

pureftpd_adduser.sh

#!/bin/bash
# ftp
ftp_root="/home/ftp"
ftp_host="ftp.host.com"
ftp_port="21"
ftp_user=$1
ftp_passwd=`pwgen -y 12 1`
ftp_owner="www-data:www-data"
ftp_perm="555"
ftp_uid="33"
ftp_gid="33"
# mysql
mysql_user="PUREUSER"
mysql_db_name="DBNAME"
mysql_table="TABLE"
mysql_passwd="PASSWORD"
# lftp
lftp_bin="/usr/bin/lftp"
 
function usage {
    echo "Usage:"
    echo "$0 ftp_user"
}
 
if [[ $1 == "" ]]; then
    usage
    exit 1
fi
 
if [ ! -d "$ftp_root/$ftp_user" ]; then
    echo "create user home dir $ftp_root/$ftp_user"
    mkdir $ftp_root/$ftp_user
    chown $ftp_owner $ftp_root/$ftp_user
    chmod $ftp_perm $ftp_root/$ftp_user
    echo "create user $ftp_user"
    mysql -u"$mysql_user" -p"$mysql_passwd" <<EOF
INSERT INTO $mysql_db_name.$mysql_table (User, status, Password, Uid, Gid, Dir, ULBandwidth, DLBandwidth, comment, ipaccess, QuotaSize, QuotaFiles) VALUES ('$ftp_user', '1', MD5('$ftp_passwd'), '$ftp_uid', '$ftp_gid', '$ftp_root/$ftp_user', '0', '0', '', '*', '0', '0');
EOF
    echo "## FTP USER ##"
    echo "host: $ftp_host"
    echo "port: $ftp_port"
    echo "login: $ftp_user"
    echo "password: $ftp_passwd"
 
    echo "## TEST ACCOUNT ##"
    if [ -f "$lftp_bin" ]; then
	$lftp_bin -u $ftp_user,$ftp_passwd localhost -e "ls;quit"
    else
	echo "lftp ($lftp_bin) not found"
    fi
    echo "done."
else
    echo "user $ftp_user already exists"
fi

fix_db_host.sh

#!/bin/bash
www_dir="/home/www"
for i in `ls $www_dir`
do
    mkdir -p /tmp/$i/
    sed -e 's/old.database.com/new.database.com/g' $i/wp-config.php > /tmp/$i/wp-config.php
    mv /tmp/$i/wp-config.php $www_dir/$i/wp-config.php
    rmdir /tmp/$i/
done

migrate_wordpress.sh

#!/bin/bash
# SSH
ssh_host="source.host.tld"
ssh_user="hio"
ssh_port="22"
ssh_key="/home/hio/.ssh/id_rsa"
www_dir="/www/blogs/"
# WWW
vhost_template="/home/hio/blog.vhost"
blog=$1
vhost_server_name=$2
# REMOTE
remote_tmp_dir="/home/hio/tmp"
remote_mysql_root="root"
remote_mysql_password="password"
# LOCAL
local_tmp_dir="/tmp"
local_mysql_root="root"
local_mysql_password="password"
 
if [ ! -f "$blog/wp-config.php" ]; then
    echo 'COPY WORDPRESS FILES...'
    scp -r -P$ssh_port -i$ssh_key $ssh_user@$ssh_host:/$www_dir/$blog .
    db_host=`grep 'DB_HOST' $blog/wp-config.php|awk -F "'" '{print $4}'`
    db_name=`grep 'DB_NAME' $blog/wp-config.php|awk -F "'" '{print $4}'`
    db_user=`grep 'DB_USER' $blog/wp-config.php|awk -F "'" '{print $4}'`
    db_password=`grep 'DB_PASSWORD' $blog/wp-config.php|awk -F "'" '{print $4}'`    
    echo "DB_HOST: $db_host"
    echo "DB_NAME: $db_name"
    echo "DB_USER: $db_user"
    echo "DB_PASSWORD: $db_password"
 
    echo "DUMP REMOTE DB TO $remote_tmp_dir/$db_name.sql"
    ssh -i$ssh_key $ssh_user@$ssh_host -p $ssh_port <<EOF>> /dev/null 2>&1
mkdir -p $remote_tmp_dir
cd $remote_tmp_dir
mysqldump --user=$remote_mysql_root --password=$remote_mysql_password -c $db_name > $remote_tmp_dir/$db_name.sql
EOF
 
    echo "GET REMOTE DB $remote_tmp_dir/$db_name.sql TO $local_tmp_dir"
    scp -i$ssh_key -P$ssh_port $ssh_user@$ssh_host:$remote_tmp_dir/$db_name.sql $local_tmp_dir
    echo "CREATE USER '$db_user'@'localhost' IDENTIFIED BY '$db_password';"
    echo "CREATE DATABASE $db_name;"
    echo "GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost' WITH GRANT OPTION;"
    mysql -u"$local_mysql_root" -p"$local_mysql_password" <<EOF
CREATE USER '$db_user'@'localhost' IDENTIFIED BY '$db_password';
CREATE DATABASE $db_name;
GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost' WITH GRANT OPTION;
EOF
 
    echo "IMPORT DUMP $local_tmp_dir/$db_name.sql TO DATABASE $db_name"
    mysql -u"$local_mysql_root" -p"$local_mysql_password" $db_name < $local_tmp_dir/$db_name.sql
 
    echo "REMOVE LOCAL/REMOTE $db_name DUMP"
    rm $local_tmp_dir/$db_name.sql
    ssh -i$ssh_key $ssh_user@$ssh_host -p $ssh_port <<EOF>> /dev/null 2>&1
rm $remote_tmp_dir/$db_name.sql
EOF
 
fi
 
if [ ! -f "/etc/apache2/sites-available/$vhost_server_name" ]; then
    echo "CREATE VHOST FOR $vhost_server_name"
    cat $vhost_template|sed "s/%BLOG_NAME%/"$vhost_server_name"/g" > /etc/apache2/sites-available/$vhost_server_name;
fi
 
if [ ! -f "/etc/apache2/sites-enabled/$vhost_server_name" ]; then
    echo "LINK /etc/apache2/sites-enabled/$vhost_server_name /etc/apache2/sites-available/$vhost_server_name"
    ln -s /etc/apache2/sites-available/$vhost_server_name /etc/apache2/sites-enabled/$vhost_server_name
fi
 
chown www-data:www-data -R $blog
<VirtualHost *:8080>
ServerAdmin romain.bureau@bayard-presse.com
DocumentRoot /home/www/%BLOG_NAME%/
ServerName %BLOG_NAME%
ErrorLog ${APACHE_LOG_DIR}/%BLOG_NAME%-error.log
CustomLog ${APACHE_LOG_DIR}/%BLOG_NAME%-access.log combined
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
<directory /home/www/%BLOG_NAME%/>
Options -Indexes +ExecCGI
AllowOverride All
order allow,deny
Allow from all
</directory>
</VirtualHost>
cd /var/www
bash /home/hio/migrate_wordpress.sh blog.hio.fr blog.hio.fr