Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jessegreathouse/959051 to your computer and use it in GitHub Desktop.
Save jessegreathouse/959051 to your computer and use it in GitHub Desktop.
Before and After Magic Methods in entities. What originally I tried to do was using __get and __set but the implementation of that made my entities properties virtually public, which was something that's a no no with doctrine. So instead of using __get __
<?php
/** @MappedSuperclass */
class MagicMethods
{
public function __get($name) {
return $this->{strtolower($name)};
}
public function __set($name, $value)
{
$this->{strtolower($name)} = $value;
}
}
<?php
$rank = new Rank;
$rank->date = $date;
$rank->value = $value;
$rank->active = 1;
$rank->site = $site;
$rank->word = $word;
$em->persist($rank);
$em->flush();
<?php
/** @MappedSuperclass */
class MagicMethods
{
public function __call($method, $args)
{
if (strpos($method, 'get') === 0) {
$name = substr($method, 3);
return $this->get($name);
} else if (strpos($method, 'set') === 0) {
$name = substr($method, 3);
return $this->set($name, $args[0]);
} else {
throw new \Exception('Method '.$method.' not found in class: ' . get_class($this));
}
}
public function get($name) {
return $this->{strtolower($name)};
}
public function set($name, $value)
{
$this->{strtolower($name)} = $value;
}
}
<?php
$rank = new Rank;
$rank->setDate($date);
$rank->setValue($value);
$rank->setActive(1);
$rank->setSite($xsite);
$rank->setWord($xword);
$em->persist($rank);
$em->flush();
@anoxic
Copy link

anoxic commented Jul 22, 2013

I'm having trouble seeing the differences between these. Set and get interfaces exactly the same way between them. ($this->{strtolower($name)}). In the second example, you can get your properties with $rank->site just as well as $rank->getSite.

Something like this keeps it all private: https://gist.github.com/anoxic/6049039

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment