class-templates.txt 12.5 KB
Newer Older
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
++ Introduction

Many times you may find classes having similar things within your models. These things may contain anything related to the schema of the component itself (relations, column definitions, index definitions etc.). One obvious way of refactoring the code is having a base class with some classes extending it.

However inheritance solves only a fraction of things. The following subchapters show how many times using Doctrine_Template is much more powerful and flexible than using inheritance.

Doctrine_Template is a class templating system. Templates are basically ready-to-use little components that your Record classes can load. When a template is being loaded its setTableDefinition() and setUp() methods are being invoked and the method calls inside them are being directed into the class in question.

++ Simple templates

In the following example we define a template called TimestampTemplate. Basically the purpose of this template is to add date columns 'created' and 'updated' to the record class that loads this template. Additionally this template uses a listener called Timestamp listener which updates these fields based on record actions.

<code type="php">
class TimestampListener extends Doctrine_Record_Listener
{
    public function preInsert(Doctrine_Event $event)
    {
        $event->getInvoker()->created = date('Y-m-d', time());
        $event->getInvoker()->updated = date('Y-m-d', time());
    }
    public function preUpdate(Doctrine_Event $event)
    {
        $event->getInvoker()->created = date('Y-m-d', time());
        $event->getInvoker()->updated = date('Y-m-d', time());
    }
}
class TimestampTemplate extends Doctrine_Template
{
    public function setTableDefinition()
    {
        $this->hasColumn('created', 'date');
        $this->hasColumn('updated', 'date');

        $this->setListener(new TimestampListener());
    }
}
</code>

Lets say we have a class called Blog that needs the timestamp functionality. All we need to do is to add loadTemplate() call in the class definition.

<code type="php">
class Blog extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('title', 'string', 200);
        $this->hasColumn('content', 'string');
    }
    public function setUp()
    {
        $this->loadTemplate('TimestampTemplate');
    }
}
</code>


++ Templates with relations

Many times the situations tend to be much more complex than the situation in the previous chapter. You may have model classes with relations to other model classes and you may want to replace given class with some extended class.

Consider we have two classes, User and Email, with the following definitions:

<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('name', 'string');
    }
    public function setUp()
    {
        $this->hasMany('Email', array('local' => 'id', 'foreign' => 'user_id'));
    }
}
class Email extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('address', 'string');
        $this->hasColumn('user_id', 'integer');
    }
    public function setUp()
    {
        $this->hasOne('User', array('local' => 'user_id', 'foreign' => 'id'));
    }
}
</code>

Now if we extend the User and Email classes and create, for example, classes ExtendedUser and ExtendedEmail, the ExtendedUser will still have a relation to the Email class - not the ExtendedEmail class. We could of course override the setUp() method of the User class and define relation to the ExtendedEmail class, but then we lose the whole point of inheritance. Doctrine_Template can solve this problem elegantly with its dependency injection solution.

In the following example we'll define two templates, UserTemplate and EmailTemplate, with almost identical definitions as the User and Email class had.

<code type="php">
class UserTemplate extends Doctrine_Template
{
    public function setTableDefinition()
    {
        $this->hasColumn('name', 'string');
    }
    public function setUp()
    {
        $this->hasMany('EmailTemplate as Email', array('local' => 'id', 'foreign' => 'user_id'));
    }
}
class EmailTemplate extends Doctrine_Template
{
    public function setTableDefinition()
    {
        $this->hasColumn('address', 'string');
        $this->hasColumn('user_id', 'integer');
    }
    public function setUp()
    {
        $this->hasOne('UserTemplate as User', array('local' => 'user_id', 'foreign' => 'id'));
    }
}
</code>

Notice how we set the relations. We are not pointing to concrete Record classes, rather we are setting the relations to templates. This tells Doctrine that it should try to find concrete Record classes for those templates. If Doctrine can't find these concrete implementations the relation parser will throw an exception, but before we go ahead of things, here are the actual record classes:

<code type="php">
class User extends Doctrine_Record
{
    public function setUp()
    {
        $this->loadTemplate('UserTemplate');
    }
}
class Email extends Doctrine_Record
{
    public function setUp()
    {
        $this->loadTemplate('EmailTemplate');
    }
}
</code>

Now consider the following code snippet. This does NOT work since we haven't yet set any concrete implementations for the templates.

<code type="php">
$user = new User();
$user->Email; // throws an exception
</code>

The following version works. Notice how we set the concrete implementations for the templates globally using Doctrine_Manager.

<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setImpl('UserTemplate', 'User')
        ->setImpl('EmailTemplate', 'Email');

$user = new User();
$user->Email;
</code>

The implementations for the templates can be set at manager, connection and even at the table level.

++ Delegate methods

Besides from acting as a full table definition delegate system, Doctrine_Template allows the delegation of method calls. This means that every method within the loaded templates is available in the record that loaded the templates. Internally the implementation uses magic method called __call() to achieve this functionality.

Lets take an example: we have a User class that loads authentication functionality through a template.

<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('fullname', 'string', 30);
    }
    public function setUp()
    {
        $this->loadTemplate('AuthTemplate');
    }
}
class AuthTemplate extends Doctrine_Template
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 16);
        $this->hasColumn('password', 'string', 16);
    }
    public function login($username, $password)
    {
        // some login functionality here
    }
}
</code>

Now you can simply use the methods found in AuthTemplate within the User class as shown above.

<code type="php">
$user = new User();

$user->login($username, $password);
</code>

You can get the record that invoked the delegate method by using the getInvoker() method of Doctrine_Template. Consider the AuthTemplate example. If we want to have access to the User object we just need to do the following:

<code type="php">
zYne's avatar
zYne committed
201
class AuthTemplate extends Doctrine_Template
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 16);
        $this->hasColumn('password', 'string', 16);
    }
    public function login($username, $password)
    {
        // do something with the Invoker object here
        $object = $this->getInvoker();
    }
}
</code>

++ Working with multiple templates

Each class can consists of multiple templates. If the templates contain similar definitions the most recently loaded template always overrides the former.

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
++ Core Templates

Doctrine comes bundled with some templates that offer out of the box functionality for your models. You can enable these templates in your models very easily. You can do it directly in your Doctrine_Records or you can specify them in your yaml schema if you are managing your models with a yaml schema file.

+++ Versionable
PHP Example
<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }
    
    public function setUp()
    {
        $this->actAs('Versionable', array('versionColumn' => 'version', 'className' => '%CLASS%Version'));
    }
}
</code>

YAML Example
<code type="yaml">
---
User:
  actAs:
    Versionable:
      versionColumn: version
      className: %CLASS%Version
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>

+++ Timestampable

The 2nd argument array is not required. It defaults to all the values that are present in the example below.

PHP Example
<code type="php">                                              
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }
    
    public function setUp()
    {
        $this->actAs('Timestampable', array('created' =>  array('name'    =>  'created_at',
                                                                'type'    =>  'timestamp',
                                                                'format'  =>  'Y-m-d H:i:s',
                                                                'options' =>  array()),
                                            'updated' =>  array('name'    =>  'updated_at',
                                                                'type'    =>  'timestamp',
                                                                'format'  =>  'Y-m-d H:i:s',
                                                                'options' =>  array())));
    }
}
</code>

YAML Example
<code type="yaml">
---
User:
  actAs:
    Timestampable:
      created:
        name: created_at
        type: timestamp
        format:Y-m-d H:i:s
        options: []
      updated:
        name: updated_at
        type: timestamp
        format: Y-m-d H:i:s
        options: []
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>

+++ Sluggable
If you do not specify the columns to create the slug from, it will default to just using the toString() method on the model.

PHP Example
<code type="php">                                              
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }
    
    public function setUp()
    {
        $this->actAs('Sluggable', array('columns' => array('username')));
    }
}
</code>
327

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
YAML Example
<code type="yaml">
---
User:
  actAs:
    Sluggable:
      columns: [username]
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>

+++ I18n
PHP Example
<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }

    public function setUp()
    {
        $this->actAs('I18n', array('fields' => array('title')));
    }
}
</code>

YAML Example
<code type="yaml">
---
User:
  actAs:
    I18n:
      fields: [title]
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>

+++ NestedSet
PHP Example
<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }

    public function setUp()
    {
        $this->actAs('NestedSet', array('hasManyRoots' => true, 'rootColumnName' => 'root_id'));
    }
}
</code>

YAML Example
<code type="yaml">
---
User:
  actAs:
    NestedSet:
      hasManyRoots: true
      rootColumnName: root_id
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>

+++ Searchable
PHP Example
<code type="php">
class User extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('username', 'string', 125);
        $this->hasColumn('password', 'string', 255);
    }

    public function setUp()
    {
        $this->actAs('Searchable', array('fields' => array('title', 'content')));
    }
}
</code>
424

425 426 427 428 429 430 431 432 433 434 435 436 437
YAML Example
<code type="yaml">
---
User:
  actAs:
    Searchable:
      fields: [title, content]
  columns:
    username:
      type: string(125)
    password:
      type: string(255)
</code>