DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Change Bidirectional Association to Unidirectional

Practical PHP Refactoring: Change Bidirectional Association to Unidirectional

Giorgio Sironi user avatar by
Giorgio Sironi
·
Sep. 05, 11 · Interview
Like (0)
Save
Tweet
Share
7.75K Views

Join the DZone community and get the full member experience.

Join For Free

this refactoring is the inverse of change unidirectional association to bidirectional . we start from a bidirectional association, where two objects reference each other; the association is simplified to only comprehend one direction, deleting one of the two back pointers.

why should i change back an association?

an unidirectional association is simpler to establish at instantiation time, and simpler to maintain : changing the object participating to one side of the association or simply removing the instance of the association is easier as it involves a single pointer (actually called handler in php).

another problem with bidirectionality is garbage collection : usually in php objects which pertained to a cycle were not deleted even if unreachable from any other scope.(both of them still have a potential reference: the other object.) thus, maintaining a bidirectional references ensured that the occupied memory would never be freed until the end of the script.

however, from php 5.3 a patch has been integrated to detect cycles and address this issue once and for all. so, performance should not be a parameter for choosing a unidirectional or bidirectional association.

an issue which will always be present instead is dependency : two classes participating to a bidirectional associations normally depend on each other, making them inseparable. class a won't be instantiable or complete with class b, and vice versa: separating their responsibilities in different classes does not help very much without independency.

the dependency cycle can be broken by the introduction of an interface to implement for one of the two sides:


however an interface is an additional moving part, and has a maintenance cost too. thus i would always prefer an unidirectional association to a perfectly decoupled bidirectional one.

when should i simplify?

whenever possible: when there are no accesses to the field reference from one side, that field reference is not useful anymore and can be deleted with this refactoring.

in the special case of an orm which needs a particular side to exist, you may have discovered a particular configuration allowing for unidirectional associations in the one-to-many case.

everytime i say "one side is not used" you can also read "one side is really seldom used". there are alternatives for obtaining a reference to maintaining it all the time (such as passing it as a method parameter when required), so the refactoring to unidirectional association can always be considered.

steps

consider the one of the two references which you want to remove. for the refactoring to be feasible, one of these options must occur:

  • the reference must not be used ;
  • there must be another way for obtaining a reference or for getting a message to the other object, but this is the subject of other refactorings;
  • the other object can be added as an argument to the methods which use it, changing the reference from a field to a parameter one.

for example, when a private field is used by a strong minority of methods in a class, is on its way to become a parameter to improve the cohesion of the class itself. the same occurs in this special case.

  1. the reference should be checked for usage or substituted with a parameter or another algorithm, according to the case this scenario falls in.
  2. remove all assignments to the field, and the calls to the methods that assigned the field if they become empty.

for example, by eliminating the noncontrolling side , you will eliminate the call from the controlling one. while by eliminating the controlling side, which is rarer, you will eliminate the method on that side and change the name of the noncontrolling one to become part of the api of the class.

example

initially , we check the field phonenumber::$user is not used anymore. we could also pass the user object as a parameter in __tostring() in case it's referenced (of course we will need to change the name as it won't be a magic method anymore.)

<?php
class changebidirectionalassociationtounidirectional extends phpunit_framework_testcase
{
    public function testphonenumbersdonotneedtorefertousers()
    {
        $user = new user('giorgio');
        $user->addphonenumber(new phonenumber('012345'));
        $this->assertequals("012345\n", $user->phonenumberslist());
    }
}

class user
{
    private $name;
    private $phonenumbers;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function addphonenumber(phonenumber $phonenumber)
    {
        $this->phonenumbers[] = $phonenumber;
        $phonenumber->internalsetuser($this);
    }

    public function phonenumberslist()
    {
        $list = '';
        foreach ($this->phonenumbers as $number) {
            $list .= "$number\n";
        }
        return $list;
    }

    public function getname()
    {
        return $this->name;
    }
}

class phonenumber
{
    private $number;

    /**
     * @var user
     */
    private $user;

    public function __construct($number)
    {
        $this->number = $number;
    }

    public function internalsetuser(user $u)
    {
        $this->user = $u;
    }

    public function __tostring()
    {
        return $this->number;
    }
}

we remove the assignment code, and the field. the code still passes the test.

class user
{
    // ...

    public function addphonenumber(phonenumber $phonenumber)
    {
        $this->phonenumbers[] = $phonenumber;
        $phonenumber->internalsetuser($this);
    }
}

class phonenumber
{
    private $number;

    public function __construct($number)
    {
        $this->number = $number;
    }

    public function internalsetuser(user $u)
    {
    }

    public function __tostring()
    {
        return $this->number;
    }
}

we can now remove the api of the noncontrolling side (since it's this side that has no references to the other.) the phonenumber objects are now simpler and they do not depend on the user class anymore.

class user
{
    private $name;
    private $phonenumbers;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function addphonenumber(phonenumber $phonenumber)
    {
        $this->phonenumbers[] = $phonenumber;
    }

    public function phonenumberslist()
    {
        $list = '';
        foreach ($this->phonenumbers as $number) {
            $list .= "$number\n";
        }
        return $list;
    }

    public function getname()
    {
        return $this->name;
    }
}

class phonenumber
{
    private $number;

    public function __construct($number)
    {
        $this->number = $number;
    }

    public function __tostring()
    {
        return $this->number;
    }
}
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Important Data Structures and Algorithms for Data Engineers
  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?
  • How To Handle Secrets in Docker
  • Building the Next-Generation Data Lakehouse: 10X Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: