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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 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
  • Inheritance in PHP: A Simple Guide With Examples

Trending

  • The 7 Pillars of Meeting Design: Transforming Expensive Conversations into Decision Assets
  • Solving the Mystery: Why Java RSS Grows in Docker on M1 Macs
  • RAG Done Right: When to Use SQL, Search, and Vector Retrieval and How To Combine Them
  • Ten Years of Beam: From Google's Dataflow Paper to 4 Trillion Events at LinkedIn
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Introduce Foreign Method

Practical PHP Refactoring: Introduce Foreign Method

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Aug. 03, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
8.3K 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.

Related

  • 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
  • Inheritance in PHP: A Simple Guide With Examples

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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