10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: Compon<strong>en</strong>t Overview 180<br />

Listing<br />

10-77<br />

// test.php<br />

// ...<br />

$users[0]->username = "Jack Daniels";<br />

$users[1]->username = "John Locke";<br />

Accessing elem<strong>en</strong>ts with get()<br />

Listing<br />

10-78<br />

echo $users->get(1)->username;<br />

Adding new Elem<strong>en</strong>ts<br />

Wh<strong>en</strong> accessing single elem<strong>en</strong>ts of the collection and those elem<strong>en</strong>ts (records) don't exist<br />

<strong>Doctrine</strong> auto-adds them.<br />

In the following example we fetch all users from database (there are 5) and th<strong>en</strong> add couple<br />

of users in the collection.<br />

As with PHP arrays the indexes start from zero.<br />

Listing<br />

10-79<br />

// test.php<br />

// ...<br />

$users = $userTable->findAll();<br />

echo count($users); // 5<br />

$users[5]->username = "new user 1";<br />

$users[6]->username = "new user 2";<br />

You could also optionally omit the 5 and 6 from the array index and it will automatically<br />

increm<strong>en</strong>t just as a PHP array would:<br />

Listing<br />

10-80<br />

// test.php<br />

// ...<br />

$users[]->username = 'new user 3'; // key is 7<br />

$users[]->username = 'new user 4'; // key is 8<br />

Getting Collection Count<br />

The <strong>Doctrine</strong>_Collection::count() method returns the number of elem<strong>en</strong>ts curr<strong>en</strong>tly in<br />

the collection.<br />

Listing<br />

10-81<br />

// test.php<br />

// ...<br />

$users = $userTable->findAll();<br />

echo $users->count();<br />

Since <strong>Doctrine</strong>_Collection implem<strong>en</strong>ts Countable interface a valid alternative for the<br />

previous example is to simply pass the collection as an argum<strong>en</strong>t for the count() function.<br />

Listing<br />

10-82<br />

// test.php<br />

// ...<br />

echo count($users);<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!