Browse Source

Proxying the __get and __isset methods from Association to Table

Jose Lorenzo Rodriguez 12 years ago
parent
commit
c3647a2dba
2 changed files with 37 additions and 0 deletions
  1. 23 0
      src/ORM/Association.php
  2. 14 0
      tests/TestCase/ORM/AssociationProxyTest.php

+ 23 - 0
src/ORM/Association.php

@@ -649,6 +649,29 @@ abstract class Association {
 	}
 
 /**
+ * Proxies property retrieval to the target table. This is handy for getting this
+ * association's associations
+ *
+ * @param string $property the property name
+ * @return \Cake\ORM\Association
+ * @throws \RuntimeException if no association with such name exists
+ */
+	public function __get($property) {
+		return $this->target()->{$property};
+	}
+
+/**
+ * Proxies the isset call to the target table. This is handy to check if the
+ * target table has another association with the passed name
+ *
+ * @param string $property the property name
+ * @return boolean true if the property exists
+ */
+	public function __isset($property) {
+		return isset($this->target()->{$property});
+	}
+
+/**
  * Get the relationship type.
  *
  * @return string Constant of either ONE_TO_ONE, MANY_TO_ONE, ONE_TO_MANY or MANY_TO_MANY.

+ 14 - 0
tests/TestCase/ORM/AssociationProxyTest.php

@@ -91,4 +91,18 @@ class AssociationProxyTest extends TestCase {
 		$this->assertEquals(1, $remaining);
 	}
 
+/**
+ * Tests that it is possible to get associations as a property
+ *
+ * @return void
+ */
+	public function testAssociationAsPropertyProxy() {
+		$articles = TableRegistry::get('articles');
+		$authors = TableRegistry::get('authors');
+		$articles->belongsTo('authors');
+		$authors->hasMany('comments');
+		$this->assertTrue(isset($articles->authors->comments));
+		$this->assertSame($authors->association('comments'), $articles->authors->comments);
+	}
+
 }