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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • AI Is Making PHP Cool Again
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • How Laravel Developers Handle Database Migrations Without Downtime
  • Migrating from Monolith to Microservices Using PHP: A Step-by-Step Guide

Trending

  • The Request Timed Out, But the Payment Succeeded: Building Retry-Safe Mobile APIs
  • Who Should Grade Your AI? Rules vs LLM Judges vs Humans
  • Kubernetes Operations Playbook: The Essentials for Keeping Scale, Complexity, and Drift Under Control
  • Why Incident Response Needs Memory, Not Just Intelligence

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Introduce Foreign Method

Practical PHP Refactoring: Introduce Foreign Method

By 
Giorgio Sironi
·
Aug. 03, 11 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • AI Is Making PHP Cool Again
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • How Laravel Developers Handle Database Migrations Without Downtime
  • Migrating from Monolith to Microservices Using PHP: A Step-by-Step Guide

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook