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
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Introduce Foreign Method

Practical PHP Refactoring: Introduce Foreign Method

Giorgio Sironi user avatar by
Giorgio Sironi
·
Aug. 03, 11 · Interview
Like (0)
Save
Tweet
Share
7.43K Views

Join the DZone community and get the full member experience.

Join For Free

A new method is needed, as we are factoring out some lines of code. It would be nice to have it available on a class which already has all the fields to execute it, but unfortunately we cannot modify original code (because it's part of a library, or it's bundled with PHP.)

A classic example of Introduce Foreign Method is cause by a missing method on ArrayObject, or SplQueue, or other external classes. The first place to place a new method is the object the code works with, since it's cohesive with the rest of the data. The second best place is the client object, although the method could get duplicated in different clients. A Foreign Method is a method created in the client code to complete the functionality of a source object.

How it works

The source object becomes a first additional argument of the Foreign Method: Python and some other languages reflects this with the self first argument, which makes refactoring Foreign Methods into normal ones easier. For a PHP- example, consider PHPUnit: I use Foreign Methods in my test cases to wrap $this->getMock() multiple usages. I factor away the adaptation to the Api (use of false arguments or MockBuilder) and leave as arguments the variability of the mocks, like the number of calls or the expected parameters.

A Foreign Method is a work-around: if you have the possibility to change the source class, definitely go for that. Another alternative is to introduce a wrapper, when you can modify the lifecycle in order to inject a wrapper in the client code instead of the original object. It's not the case for PHPUnit (you extend the class), but it is for SplQueue and other collection objects; wrapping has also other benefits which will be shown in the next articles.

Steps

  1. Create the method in the client class.
  2. Make the server object the first parameter of the method, if it cannot be passed already through $this (in case it's referenced by a field).
  3. Substitute the duplicated code with method calls.

Fowler suggests also to comment the method calling it Foreign Method and saying it should be moved onto the server object when it will become possible.

Example

Initially, we're using an ArrayObject and continuing to ordering it after each addition of an element:

<?php
class IntroduceForeignMethod extends PHPUnit_Framework_TestCase
{
    public function testLinksAreViewedInOrder()
    {
        $links = new LinkGroup();
        $links->addUrl('twitter.com');
        $links->add('plus.google.com', 'Google+');
        $links->add('facebook.com', 'Facebook');
        $expected = "<a href=\"facebook.com\">Facebook</a>\n"
                  . "<a href=\"plus.google.com\">Google+</a>\n"
                  . "<a href=\"twitter.com\">twitter.com</a>";
        $this->assertEquals($expected, $links->__toString());
    }
}

class LinkGroup
{
    private $links;

    public function __construct()
    {
        $this->links = new ArrayObject();
    }

    public function add($url, $text)
    {
        $this->links[$url] = $text;
        $this->links->asort();
    }

    public function addUrl($url)
    {
        $this->links[$url] = $url;
        $this->links->asort();
    }

    public function __toString()
    {
        $links = array();
        foreach ($this->links as $url => $text) {
            $links[] = "<a href=\"$url\">$text</a>";
        }
        return implode("\n", $links);
    }
}

We introduce a Foreign Method, newLink():

class LinkGroup
{
    private $links;

    public function __construct()
    {
        $this->links = new ArrayObject();
    }

    public function add($url, $text)
    {
        $this->newLink($url, $text);
    }

    public function addUrl($url)
    {
        $this->newLink($url, $url);
    }

    public function __toString()
    {
        $links = array();
        foreach ($this->links as $url => $text) {
            $links[] = "<a href=\"$url\">$text</a>";
        }
        return implode("\n", $links);
    }

    private function newLink($url, $text)
    {
        $this->links[$url] = $text;
        $this->links->asort();
    }
}

We also add some comments noting that if more and more Foreign Methods pop out, a radical solution would be needed:

    /**
     * Foreign Method of the ArrayObject. Should be moved onto a newly extracted
     * collaborator which wraps the ArrayObject, or an heap-like data structure
     * should be used.
     */
    private function newLink($url, $text)
    {
        $this->links[$url] = $text;
        $this->links->asort();
    }
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • REST vs. Messaging for Microservices
  • HTTP vs Messaging for Microservices Communications
  • Full Lifecycle API Management Is Dead

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: