kishanio
kishanio

Reputation: 7079

Creating Composer Package

I'm trying to create a composer package & i understand the basic workflow like of creating composer.json, auto loading and creating classes under src directory.

There is one small programming misunderstanding i have is that almost all the other packages i'm reading has interfaces and a class implementing them. I don't understand need of interfaces in this context and why we need them. I have never used interface or i'm not sure if i understand its general use case. It would be nice if someone can help me understand it.

Beside the other question i had in context to composer is how do i test / run a composer project whilst i create it?

Beside this projects that i'm referring has a command directory inside src i don't understand significance of this or its use case too. I guess it has something to do with symfony php console command.

Also there is a bin directory at source, now how is that useful.

Sorry if i'm being naive here but i'm just trying to understand which components fall where and why is it like that. I couldn't find a composer tutorial online past creating composer.json

Upvotes: 1

Views: 259

Answers (1)

Cryszon
Cryszon

Reputation: 387

You are asking a lot of questions at once, but I'll try to at least address interfaces, since I believe that's the most important one.

Interfaces are mostly used with Dependency Injection. They define methods without actually caring how the methods are actually implemented. A class may depend on an interface instead of an actual (concrete) class, which allows an easy way to swap components. Below is an example of how one might use interfaces.

interface PostsInterface {
    public function getPosts();
}

class JsonPostFetcher implements PostsInterface {
    public function getPosts() {
        // Load posts from JSON files here
    }
}

class MySqlPostFetcher implement PostsInterface {
    public function getPosts {
        // Load posts from a MySQL database
    }
}

class Blog {
    public function __construct(PostsInterface $fetcher) {
        // Load posts from either JSON or a database
        // depending on which fetcher is provided
        $posts = $fetcher->getPosts();
    }
}

Using this method anyone can now write their own code to provide posts from an external API ApiPostFetcher, SQLite Database SqlitePostFetcher, Serialized PHP files SerializedPostFetcher etc. One could even write a DymmyPostFetcher that simply returns a pretermined array of posts that could be used for testing purposes. You can then use any implementation of PostsInterface in your blog like in the following example.

$fetcher = new JsonPostFetcher(); // You can provide different fetchers here.
$blog = new Blog($fetcher);

If you're unfamiliar with dependency injection, I highly recommend learning it, since it will be especially useful in writing modular code.

Upvotes: 2

Related Questions