Code News

Creating a jQuery Plugin for Long Shadow Design

  • What You'll Be Creating

    Long shadow design is a variation of flat design to which shadows are added, creating the illusion of depth and resulting in a design that looks three-dimensional. In this tutorial we will be creating a jQuery plugin that will allow us to easily transform a flat icon by adding a fully customizable long shadows icon.

    If you are interested in a complete jQuery plugin for adding long shadows to icons and text, check out the Long Shadow jQuery Plugin on CodeCanyon.

    In this tutorial we will take a look at the elements of long shadow design, and we will create a simple jQuery plugin that will allow us to control these elements. 

    Let's get started!

    What Are the Elements of Long Shadow Design?

    Let's break apart the elements that make up a long shadow design. We can observe that we have:

    • The main element, or the element casting the shadow.
    • The shadow length, usually very long and therefore giving the name of the effect. The shadow length also gives the illusion that the main element has depth.
    • The shadow direction or angle. In the real world, this is determined by the light source position. As a rule, all the shadows cast by a light source have the same direction.
    • The shadow color and opacity. The light source color affects the color of the shadows. Also, the stronger the light source is, the darker and crisper the shadows.

    These elements put together create the illusion that the main element is not flat, but actually a 3D object that casts a shadow.

    Now let's create the jQuery plugin that would allow us to control these elements.

    Creating the Long Shadows jQuery Plugin

    To create the jQuery long shadows plugin, we will set up a basic jQuery plugin project structure like this:

    • Create a folder to hold the project files. Let's call this folder long-shadows-jquery-plugin.
    • Inside the project folder, create a file and call it index.html. This will contain our HTML code.
    • Create a file, call it jquery.longshadows.js, and place it in the folder. This will contain the JavaScript code for our jQuery plugin.
    • To keep things separated, we will also create another JavaScript file in this folder and name it script.js. This will make use of the jQuery plugin that we are just creating.
    • In the project folder, also place the heart.png icon that you can find in the attachments for this tutorial.

    Our index.html will contain a basic HTML structure and will also include jQuery and our JavaScript files. We need to include the jQuery library because we will be implementing a jQuery plugin. The index.html file should look like this:

    <html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.longshadows.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <img src="heart.png" id="logo"> </body> </html>

    The jquery.longshadows.js file will contain the jQuery plugin code, and we implement it like this:

    (function($) { $.fn.longshadows = function(options) { var settings = $.extend({ //options defaults go here ... }, options); //this applies the plugin to all matching elements return this.each(function() { //code of the plugin comes here ... }); } })(jQuery);

    We will call the plugin from the script.js file. For this tutorial, we will implement the parameters we have mentioned in the previous chapter:

    • shadowColor: The color of the shadow that our element casts.
    • shadowLength: The length of the cast shadow.
    • shadowAngle: The angle of the shadow.
    • shadowOpacity: How opaque or transparent the shadow is.
    • spacing: This is an attribute we did not mention in the previous section. However, we need this to allow the expansion of the space around the element for which we create the long shadows. In this way, the effect will be more visible.

    Let's start the implementation. To create the long shadow, we will make use of the HTML5 canvas component. We can create an in-memory canvas on which we will draw a copy of the original image element and its shadow. To draw the shadow, we will simply draw copies of the image element one on top of another, with a slight offset.

    The number of copies and the offset are calculated using a simple polar coordinates transformation based on the shadowLength and shadowAngle parameters. Also, we will have to color these copies according to the color of the shadow set by the shadowColor parameter. 

    Because we draw the shadow as multiple images on top of each other, we will draw them in reverse order, from back to front, starting with the piece of the shadow furthest from the image element. Then we have to set the opacity of the resulting shadow via the shadowOpacity parameter.

    After drawing the shadow, we will simply draw the original image on top.

    Let's see how this translates into code in the jquery.longshadows.js file:

    (function($) { $.fn.longshadows = function(options) { var settings = $.extend({ shadowColor: "black", shadowLength: 100, shadowAngle: 45, shadowOpacity: 100, spacing: 0 }, options); return this.each(function() { var img = this; img.onload = function() { var self = this; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = self.width + settings.spacing; canvas.height = self.height + settings.spacing; for (var r = settings.shadowLength; r >= 1; r--) { var x = Math.round(r * Math.cos(settings.shadowAngle * Math.PI / 180)); var y = Math.round(r * Math.sin(settings.shadowAngle * Math.PI / 180)); ctx.save(); ctx.translate(x + settings.spacing / 2, y + settings.spacing / 2); ctx.drawImage(self, 0, 0); ctx.globalCompositeOperation = 'source-in'; ctx.fillStyle = settings.shadowColor; ctx.rect(0, 0, canvas.width, canvas.height); ctx.fill(); ctx.restore(); } var tempCanvas = copyCanvas(canvas, settings.shadowOpacity / 100.0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(tempCanvas, 0, 0); ctx.drawImage(self, settings.spacing / 2, settings.spacing / 2); self.onload = null; $(self).attr("src", canvas.toDataURL("image/png")); }; img.src = img.src; }); }; })(jQuery); function copyCanvas(canvas, opacity) { var canvasDest = document.createElement("canvas"); canvasDest.width = canvas.width; canvasDest.height = canvas.height; canvasDest.getContext("2d").globalAlpha = opacity; canvasDest.getContext("2d").drawImage(canvas, 0, 0); return canvasDest; }

    The plugin is configurable by sending the parameters via the options parameter. These parameters will be merged with the default values and stored in the settings variable. This allows us to quickly use the plugin if we want, without having any parameters passed to it.

    The img variable will hold a reference to the original image element on which we apply the effect. We need to hook into the onload event of the image to make sure that the image is fully loaded when the effect is applied. Also, you will note that after the onload function we have img.src = img.src;. This will trigger the onload function, since we are not sure about the order in which the browser loads the image and the script.

    Inside the onload handler, we create the in-memory canvas element on which we will draw the end result, with the same size as the image plus the spacing. Then, starting from the furthest point towards the center, we draw copies of the image on the canvas using the polar coordinates transformation for the offset of the image drawn:

    var x = Math.round(r * Math.cos(settings.shadowAngle * Math.PI / 180)); var y = Math.round(r * Math.sin(settings.shadowAngle * Math.PI / 180));

    To draw the image on the canvas, we use the canvas 2D context and call the drawImage() function. This will draw a copy of the image onto the canvas, but what we need is a colored version of it. To do this, we make use of the canvas compositing operations. In our case, using source-in together with a rectangle colored with the shadowColor will result in an image with the same shape as the original image but with the color set to shadowColor. 

    Please note that if you have an image with multiple colors, the result will be all in the same color, as indicated by shadowColor, which is correct in our case because we are drawing a shadow, and a shadow is usually the same color.

    The for loop takes care of drawing the shadow; however, it's drawn at full opacity. We would like to be able to set the shadow opacity using the shadowOpacity parameter. To do this, we use the copyCanvas() function, which makes use of a temporary canvas and sets the opacity of the canvas content to the specified value.

    We have to do this at the end, when the entire shadow has been drawn, otherwise stacking transparent images on top of each other would result in a gradient effect.

    Let's take a look at the last two lines of the onload handler:

    self.onload = null; $(self).attr("src", canvas.toDataURL("image/png"));

    The first line removes the onload handler from the image. We do this because in the next line we would like to set the image drawn on the canvas as the new src for the original image. If we did not remove the handler then we would have gone into an infinite loop.

    How Do We Use the jQuery Long Shadows Plugin?

    Now that we have implemented the plugin, let's see how we can actually use it and what result it produces. For this we will use the script.js file, where we will call the plugin we have just created.

    The simplest way to call the plugin is:

    $(document).ready(function(){ $("#logo").longshadows(); });

    This instructs the browser that when the page finishes loading, it should apply the longshadows plugin to the element with the ID logo.

    Calling the plugin like this will make use of the default parameters. Since the result is not looking too great with these default parameters, let's see how we can change that. Let's call the plugin like this:

    $(document).ready(function(){ $("#logo").longshadows({ spacing:50, shadowOpacity:30, shadowAngle:30, shadowLength:400 }); });

    Which results in an image like this:

    Since this plugin is configurable and can be applied to any image, to multiple images, and with endless combinations of parameter values, imagination is your only limit. If we adjust the HTML inside index.html like this:

    <html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.longshadows.js"></script> <script type="text/javascript" src="script.js"></script> <style type="text/css"> body{ background:rebeccapurple; padding: 0; margin:0; } .text{ display: inline-block; margin-top: 50px; width: 400px; } h1 { color:white; font-family: sans-serif; font-size:46px; } p{ color:white; font-size:18px; } #logo{ vertical-align: top; } </style> </head> <body> <img src="heart.png" id="logo"> <div class="text"> <h1>Long Shadows jQuery Plugin</h1> <p>Long shadow design is a variation of flat design to which shadows are added creating the illusion of depth and resulting in a design that looks 3-dimensional.</p> </div> </body> </html>

    Further, if we call the plugin from script.js with these parameters:

    $(document).ready(function(){ $("img").longshadows({ spacing:150, shadowOpacity:20, shadowAngle:160, shadowLength:400, shadowColor:'#330000' }); });

    We get this result, which is perfect for a website header design:

    Also, other examples using different images:

    <html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.longshadows.js"></script> <script type="text/javascript" src="script.js"></script> <style type="text/css"> .text{ display: inline-block; margin-top: 0px; margin-left: 10px; width: 400px; } h1 { font-family: sans-serif; font-size:36px; margin-top: 0; } p{ font-size:14px; } #logo{ vertical-align: top; } </style> </head> <body> <img style="background-color:#e37e52;" src="tutsplus.png" id="logo"> <div class="text"> <h1>Tuts+</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </body> </html>

    For this, we make use of the tutsplus.png image that you can download from the attachments. Please note that we are able to combine the plugin with CSS styles, in this example adding the color rectangle around the icon.

    Congratulations

    You now have the basics for creating a jQuery plugin which adds long shadows to your icons. You can build on top of this plugin and make it work for text, for example, or to combine multiple images and shadow effects.

    If you are interested in a complete long shadows plugin with even more configuration options, check out this CodeCanyon item: Long Shadow jQuery Plugin.

    1 day 4 hours ago

Android Design Patterns: The Singleton Pattern

  • What Is the Singleton Pattern?

    The Singleton Pattern is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class. This Singleton class may be responsible for instantiating itself, or you can delegate the object creation to a factory class.  

    Let's use the example of a cellphone and its owner. A phone is typically owned by a single person, while a person can own many phones. Anytime one of these phones rings, the same owner picks it up. 

    Benefits of the Singleton Pattern

    In a typical Android app, there are many objects for which we only need one global instance, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClient, HttpLoggingInterceptor, Retrofit, Gson, SharedPreferences, the repository class, etc. If we were to instantiate more than one of these types of objects, we'd run into problems like incorrect app behaviour, resource overuse, and other confusing results. 

    Implementation

    It's quite easy to implement this pattern. The following code snippet shows how a Singleton is created.

    public class Singleton { private static Singleton INSTANCE = null; // other instance variables can be here private Singleton() {}; public static Singleton getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton(); } return(INSTANCE); } // other instance methods can follow }

    In the code above, we have a static variable INSTANCE to hold an instance of the class. We also made the constructor private because we want to enforce noninstantiability—the class can only instantiate itself. The method getInstance() guarantees that the class is instantiated, if it has not been, and that it's returned to the caller. 

    Example: Creating a Single Instance of Retrofit

    Retrofit is a popular library to connect a REST web service by translating the API into Java interfaces. To learn more about it, check out my tutorial here on Envato Tuts+. 

    In an Android app, you'll need a single global instance of a Retrofit object so that other parts of an app such as a UserProfileActivity or SettingsActivity can use it to execute a network request without the need to create an instance every single time we need it. Creating multiple instances would pollute our app with unused retrofit objects, thereby occupying unnecessary memory on an already memory-constrained mobile device. 

    import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }

    So anytime client A calls RetrofitClient.getClient(), it creates the instance if it has not been created already, and then when client B calls this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one. 

    Dealing With Multithreading

    In the Android system, you can spin off multiple threads to perform different tasks. These threads can end up executing the same code block simultaneously. In the case of the Singleton class above, this could lead to the creation of multiple object instances, which violates the contract of a Singleton. So our Singleton code snippet method getInstance() is not thread safe. We'll now look at ways to make it thread safe.

    Synchronize the getInstance() Method 

    One of the ways to make the singleton code thread safe is by making the method getInstance() a synchronized one. Doing this only allows one thread to run the method at a time, forcing every other thread to be in a wait or blocked state. 

    public class Singleton { private static Singleton INSTANCE = null; // other instance variables can be here private Singleton() {}; public static synchronized Singleton getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton(); } return(INSTANCE); } // other instance methods can follow }

    This approach makes our code thread safe, but it is an expensive operation. In other words, this can slow down performance. So you have to investigate and see if the performance cost is worthwhile in your application.

    Eagerly Create an Instance

    Another approach to deal with multiple threads accessing the singleton is to create the Singleton instance immediately when the class is loaded or initialized (by the Android ClassLoader in the Dalvik VM). This makes the code thread safe. Then the object instance will already be available before any thread accesses the INSTANCE variable. 

    public class Singleton { private static Singleton INSTANCE = new Singleton(); // other instance variables can be here private Singleton() {}; public static Singleton getInstance() { return(INSTANCE); } // other instance methods can follow }

    A drawback to this approach is that you can end up creating an object that might never be used, thereby occupying unnecessary memory. So this approach should typically only be used if you are sure that the singleton will be accessed. 

    Bonus: Using Dagger 2

    A dependency injection library such as Dagger can help you wire up your object dependencies and create singletons by using the @Singleton annotation. This will ensure that the object is only initialized once throughout the application lifecycle.

    @Module public class NetworkModule { @Provides @Singleton public Gson gson() { GsonBuilder gsonBuilder = new GsonBuilder(); return gsonBuilder.create(); } @Provides @Singleton public HttpLoggingInterceptor loggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor( message -> Timber.i(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } @Provides @Singleton public Cache cache(File cacheFile) { return new Cache(cacheFile, 10 * 1000 * 1000); //10MB Cache } @Provides @Singleton public File cacheFile(@ApplicationContext Context context) { return new File(context.getCacheDir(), "okhttp_cache"); } @Provides @Singleton public OkHttpClient okHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache) { return new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .cache(cache) .build(); } @Provides @Singleton public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okHttpClient) .baseUrl("you/base/url") .build(); } }

    In the code above, we create a single instance of Gson, Cache, File, OkHttpClient and finally Retrofit types to be provided from the dependency graph generated by Dagger. 

    To learn more about Dagger 2, check out our tutorial here on Envato Tuts+. 

    Conclusion

    In this short tutorial, you learned about the Singleton pattern in Android: what it is, the benefits of using it, how to implement it by writing your own, and some ways of dealing with multiple threads. I also showed you how to use a third-party library such as Dagger 2. 

    In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!

    1 day 7 hours ago

How to Register & Use Laravel Service Providers

  • If you've ever come across the Laravel framework, it's highly unlikely that you haven't heard of service containers and service providers. In fact, they're the backbone of the Laravel framework and do all the heavy lifting when you launch an instance of any Laravel application.

    In this article, we're going to have a glimpse of what the service container is all about, and following that we'll discuss the service provider in detail. In the course of this article, I'll also demonstrate how to create a custom service provider in Laravel. Once you create a service provider, you also need to register it with the Laravel application in order to actually use it, so we'll go through that as well.

    There are two important methods, boot and register, that your service provider may implement, and in the last segment of this article we'll discuss these two methods thoroughly.

    Before we dive into the discussion of a service provider, I'll try to introduce the service container as it will be used heavily in your service provider implementation.

    Understand Service Containers and Service ProvidersWhat Is a Service Container?

    In the simplest terms, we could say that the service container in Laravel is a box that holds various components' bindings, and they are served as needed throughout the application.

    In the words of the official Laravel documentation:

    The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.

    So, whenever you need to inject any built-in component or service, you could type hint it in your constructor or method, and it'll be injected automatically from the service container as it contains everything you need! Isn't that cool? It saves you from manually instantiating the components and thus avoids tight coupling in your code.

    Let's have a look at a quick example to understand it.

    Class SomeClass { public function __construct(FooBar $foobarObject) { // use $foobarObject object } }

    As you can see, the SomeClass needs an instance of FooBar to instantiate itself. So, basically, it has a dependency that needs to be injected. Laravel does this automatically by looking into the service container and injecting the appropriate dependency.

    And if you're wondering how Laravel knows which components or services to include in the service container, the answer is the service provider. It's the service provider that tells Laravel to bind various components into the service container. In fact, it's called service container bindings, and you need to do it via the service provider.

    So it's the service provider that registers all the service container bindings, and it's done via the register method of the service provider implementation.

    That should bring another question on the table: how does Laravel know about various service providers? Did you just say anything? I've just heard someone saying that, Laravel should figure that out automatically too! Oh boy, that's too much to ask: Laravel is a framework not a superman, isn't it? Kidding apart, that's something you need to inform Laravel explicitly.

    Go ahead and look at the contents of the config/app.php file. You'll find an array entry that lists all the service providers that will be loaded during the bootstrapping of the Laravel application.

    'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ Laravel\Tinker\TinkerServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, ],

    So, that was the service container at your disposal. From the next section onwards, we'll focus on the service provider, which is the main topic of this article!

    What Is a Service Provider?

    If the service container is something that allows you to define bindings and inject dependencies, then the service provider is the place where it happens.

    Let's have a quick look at one of the core service providers to understand what it does. Go ahead and open the vender/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php file.

    public function register() { $this->app->singleton('cache', function ($app) { return new CacheManager($app); }); $this->app->singleton('cache.store', function ($app) { return $app['cache']->driver(); }); $this->app->singleton('memcached.connector', function () { return new MemcachedConnector; }); }

    The important thing to note here is the register method, which allows you to define service container bindings. As you can see, there are three bindings for the cache, cache.store and memcached.connector services.

    Basically, we're informing Laravel that whenever there's a need to resolve a cache entry, it should return the instance of CacheManager. So we're just adding a kind of mapping in the service container that can be accessed via $this->app.

    This is the proper way to add any service to a Laravel service container. That also allows you to realize the bigger picture of how Laravel goes through the register method of all service providers and populates the service container! And as we've mentioned earlier, it picks up the list of service providers from the config/app.php file.

    And that's the story of the service provider. In the next section, we'll discuss how to create a custom service provider so that you can register your custom services into the Laravel service container.

    Create Your Custom Service Provider

    Laravel already comes with a hands-on command-line utility tool, artisan, which allows you to create template code so that you don't have to create it from scratch. Go ahead and move to the command line and run the following command in your application root to create a custom service provider.

    $php artisan make:provider EnvatoCustomServiceProvider Provider created successfully.

    And that should create the file EnvatoCustomServiceProvider.php under the app/Providers directory. Open the file to see what it holds.

    <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class EnvatoCustomServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { // } }

    As we discussed earlier, there are two methods, boot and register, that you'll be dealing with most of the time when you work with your custom service provider.

    The register method is the place where you define all your custom service container bindings. On the other hand, the boot method is the place where you can consume already registered services via the register method. In the last segment of this article, we'll discuss these two methods in detail as we'll go through some practical use cases to understand the usage of both the methods.

    Register Your Custom Service Provider

    So you've created your custom service provider. That's great! Next, you need to inform Laravel about your custom service provider so that it can load it along with other service providers during bootstrapping.

    To register your service provider, you just need to add an entry to the array of service providers in the config/app.php file.

    'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ Laravel\Tinker\TinkerServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\EnvatoCustomServiceProvider::class, ],

    And that's it! You've registered your service provider with Laravel's scheme of things! But the service provider we've created is almost a blank template and of no use at the moment. In the next section, we'll go through a couple of practical examples to see what you could do with the register and boot methods.

    Go Through the Register and Boot Methods

    To start with, we'll go through the register method to understand how you could actually use it. Open the service provider file app/Providers/EnvatoCustomServiceProvider.php that was created earlier and replace the existing code with the following.

    <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Library\Services\DemoOne; class EnvatoCustomServiceProvider extends ServiceProvider { public function boot() { } public function register() { $this->app->bind('App\Library\Services\DemoOne', function ($app) { return new DemoOne(); }); } }

    There are two important things to note here:

    • We've imported App\Library\Services\DemoOne so that we can use it. The DemoOne class isn't created yet, but we'll do that in a moment.
    • In the register method, we've used the bind method of the service container to add our service container binding. So, whenever the App\Library\Services\DemoOne dependency needs to be resolved, it'll call the closure function, and it instantiates and returns the App\Library\Services\DemoOne object.

    So you just need to create the app/Library/Services/DemoOne.php file for this to work.

    <?php namespace App\Library\Services; class DemoOne { public function doSomethingUseful() { return 'Output from DemoOne'; } }

    And here's the code somewhere in your controller where the dependency will be injected.

    <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Library\Services\DemoOne; class TestController extends Controller { public function index(DemoOne $customServiceInstance) { echo $customServiceInstance->doSomethingUseful(); } }

    That's a very simple example of binding a class. In fact, in the above example, there's no need to create a service provider and implement the register method as we did, since Laravel can automatically resolve it using reflection.

    A very important note from the Laravel documentation:

    There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.

    On the other hand, it would have been really useful if you had bound an interface to a certain implementation. Let's go through an example to understand it.

    Let's create a very simple interface at app/Library/Services/Contracts/CustomServiceInterface.php.

    <?php // app/Library/Services/Contracts/CustomServiceInterface.php namespace App\Library\Services\Contracts; Interface CustomServiceInterface { public function doSomethingUseful(); }

    Next, let's create two concrete implementations of this interface. Basically, we just need to create two classes that extend the CustomServiceInterface interface.

    Create the DemoOne class in app/Library/Services/DemoOne.php.

    <?php // app/Library/Services/DemoOne.php namespace App\Library\Services; use App\Library\Services\Contracts\CustomServiceInterface; class DemoOne implements CustomServiceInterface { public function doSomethingUseful() { return 'Output from DemoOne'; } }

    Similarly, DemoTwo goes in app/Library/Services/DemoTwo.php.

    <?php // app/Library/Services/DemoTwo.php namespace App\Library\Services; use App\Library\Services\Contracts\CustomServiceInterface; class DemoTwo implements CustomServiceInterface { public function doSomethingUseful() { return 'Output from DemoTwo'; } }

    Now, instead of binding a class, we'll bind an interface. Revisit EnvatoCustomServiceProvider.php and change the code as shown below.

    <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Library\Services\DemoOne; class EnvatoCustomServiceProvider extends ServiceProvider { public function boot() { } public function register() { $this->app->bind('App\Library\Services\Contracts\CustomServiceInterface', function ($app) { return new DemoOne(); }); } }

    In this case, we've bound the App\Library\Services\Contracts\CustomServiceInterface interface to the DemoOne implementation. Hence, whenever the App\Library\Services\Contracts\CustomServiceInterface dependency needs to be resolved, it instantiates and returns the App\Library\Services\DemoOne object. Now it makes more sense, doesn't it?

    Let's quickly revise the controller code as well.

    <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Library\Services\Contracts\CustomServiceInterface; class TestController extends Controller { public function index(CustomServiceInterface $customServiceInstance) { echo $customServiceInstance->doSomethingUseful(); } }

    As you may have guessed, the $customServiceInstance should be the instance of App\Library\Services\DemoOne! The beauty of this approach is that you can swap the DemoOne implementation with the other one easily.

    Let's say you want to use the DemoTwo implementation instead of DemoOne. In that case, you just need to make the following changes in the service provider EnvatoCustomServiceProvider.php.

    Find the following line:

    use App\Library\Services\DemoOne;

    And replace it with:

    use App\Library\Services\DemoTwo;

    Similarly, find this one:

    return new DemoOne();

    That should be replaced by:

    return new DemoTwo();

    The same approach can be used should you want to replace any core implementation with your own. And it's not only the bind method you could use for your service container bindings; the Laravel service container provides various ways of binding into the service container. Please check the official Laravel documentation for the complete reference.

    The next candidate is the boot method, which you could use to extend the core Laravel functionality. In this method, you could access all the services that were registered using the register method of the service provider. In most cases, you want to register your event listeners in this method, which will be triggered when something happens.

    Let's have a look at a couple of examples that require the boot method implementation.

    You want to add your own custom form field validator to Laravel.

    public function boot() { Validator::extend('my_custom_validator', function ($attribute, $value, $parameters, $validator) { // validation logic goes here... }); }

    Should you wish to register a view composer, it's the perfect place to do that! In fact, we could say that the boot method is frequently used to add view composers!

    public function boot() { View::composer( 'demo', 'App\Http\ViewComposers\DemoComposer' ); }

    Of course, you want to import a facade Illuminate\Support\Facades\View in your service provider in the first place.

    In the same territory, you could share the data across multiple views as well!

    public function boot() { View::share('key', 'value'); }

    It can also be used to define explicit model bindings.

    public function boot() { parent::boot(); Route::model('user', App\User::class); }

    These were a few examples to demonstrate the usage of the boot method. The more you get into Laravel, the more reasons you'll find to implement it!

    And with that, we've reached the end of this article. I hope you've enjoyed the topics that were discussed throughout this article.

    Conclusion

    It was the discussion of service providers that was the center attraction of this article, although we began our article with the service container as that was an important ingredient in order to understand the service provider.

    Following that, we developed a custom service provider, and in the latter half of the article we went through a couple of practical examples.

    For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study at Envato Market.

    If you've any queries or comments, just shoot it using the feed below!

    2 days 4 hours ago

10 Best CRM & Project Management PHP Scripts

  • As a freelancer and someone who works with a small business, I have experienced the pain points of project management. The solution is usually an ever-changing mix of various apps and services that never feel quite right. I am always interested in trying something new since there always seems to be room for improvement. However, there's one solution I haven't tried: hosting my own CRM and project management solution.

    Setting up your own CRM and project management system not only keeps your data completely in your control, it also consolidates everything into one place. One admin. One URL. It's a beautiful thing.

    In an effort to find a solution for myself, I've compiled a list of the 10 best CRM and project management PHP scripts freelancers and small businesses should consider:

    1. Freelance Cockpit 3 - Project Management and CRM

    Freelancers and small businesses can streamline their project management, from the first estimate to the final billing and everything in between, with Freelance Cockpit 3 - Project Management and CRM.

    This CRM and project management PHP script is a small investment with huge payoffs.

    Here's a quick look at some of the included features:

    • several invoice payment options, including PayPal, Stripe, and others
    • project timer and optional Google Calendar integration
    • track expenses and send estimates
    • an option for clients to create tasks
    • set up recurring invoices
    • private messaging
    • and much, much more

    As someone who is actively a freelancer, this is top on my list of possible solutions to organize and execute projects.

    Freelance Cockpit 3 - Project Management and CRM brings all the important information together, so you can focus more on what you do best.

    2. Freelance Project Invoice CRM

    The Freelance Project Invoice CRM is the number one selling CRM on CodeCanyon for good reason. All your jobs, tasks, invoicing, quotes, support tickets, and much more are brought together beautifully into one place.

    Stop using multiple solutions across multiple platforms and pull everything together into one place.

    This self-hosted solution features:

    • basic inventory and product unit types
    • track income and expenses
    • email ticket support system
    • member subscriptions
    • set up staff members
    • track tasks and time
    • customer details
    • customizable
    • and much, much more

    The more I look at this CRM, the more I am interested in giving it a test drive.

    Freelance Project Invoice CRM is a clear stand-out among CRM and project management solutions.

    3. Freelancer Office

    Freelancers take notice: Freelancer Office is an excellent choice for CRM and project management. Don't let its good looks and solid design make you think it lacks power—this CRM gets the job done.

    From project start to finish, you'll be able to meet your clients' needs better than ever.

    Features include:

    • full estimate and invoicing system
    • file sharing and discussions
    • bug tracking and ticketing
    • private messaging
    • email notifications
    • recurring invoices
    • online payments
    • and much more

    You might not be able to hire someone to work in your office, but you can afford to hire the Freelancer Office.

    4. Perfex - Powerful Open Source CRM

    This CRM and project management solution is more than just a way to organize your tasks and easily send out invoices. Perfex - Powerful Open Source CRM is about customer relationships.

    Provide your client with more than just a good product; offer them the kind of customer relationship they won't be able to find anywhere else.

    You'll find lots of helpful features:

    • see your invoices, contracts, tasks, and more in the built-in calendar
    • create a customer knowledge base
    • goal tracking and reporting
    • full-featured customer area
    • lead management tool
    • a full support system
    • assign tasks
    • and much, much more

    I found the project proposal creation tool and helpful customer service toolset to be one of the best you'll find. This isn't just something to make your business run better, it's a new service you can offer your clients.

    Every CRM and project management system has its own angle, and Perfex - Powerful Open Source CRM offers top-notch tools for your customers.

    5. Freelance Manager

    You can't talk about CRM and project management without mentioning the Freelance Manager. This handsome app is simple but powerful. With the admin and client areas fully responsive, this will serve you well from your desk or on the go.

    Some features you'll find include:

    • messaging and staff management
    • payment gateway integration
    • workflow approval system
    • comprehensive reporting
    • visual estimate builder
    • support ticket system
    • easily create forms
    • file uploader
    • and much more

    With the ability for clients to submit tickets, upload files, and approve drafts, this not only makes managing clients easier but also offers them a great service.

    Freelance Manager is an excellent freelance manager.

    6. Ekushey Project Manager CRM

    While this CRM and project management app servers freelancers well, it adds another layer that small business with multiple team members will find extremely helpful. Ekushey Project Manager CRM introduces a full-featured project space that makes collaborating much more efficient:

    • discuss the project on a "wall"
    • organize your tasks, notes, and files.
    • use the timesheet and accept payments

    Additional features include:

    • multi-language and currency support
    • manage both projects and clients
    • income expense comparison
    • Dropbox integration
    • manage expenses
    • sidebar to-do lists
    • private message
    • project reports
    • and much, much more

    I especially like the intuitive client and profile overviews and the ease of adding people to projects.

    The Ekushey Project Manager CRM is a robust CRM and project management tool that's useful for freelancers and powerful enough for businesses with many team members.

    7. All in One Business Management Application

    The All in One Business Management Application will help you get down to business.

    While this CRM and project management tool includes many of the flagship features you can expect, there is more of an accounting focus.

    Features include:

    • multi-language support
    • support ticket system
    • order management
    • built-in help desk
    • invoicing
    • and more

    Do your business a favor, consider the All in One Business Management Application.

    8. LiveProjects - Complete Project Management CRM

    LiveProjects - Complete Project Management CRM is a powerful way to manage both your projects and team. A great companion for managing both clients and team members.

    Some of the helpful features include:

    • file sharing
    • complete user management
    • calendar with daily agenda
    • timesheets, work hours, and to do lists
    • customer management

    Easily configure:

    • customer and project types
    • project status
    • task priorities and status
    • user types
    • email templates
    • and more

    LiveProjects - Complete Project Management CRM packs a lot of punch with its powerful feature set and useful customization.

    9. Zestpro - Project Management

    Stay on track, stay on budget, stay on top of your projects with The Zestpro - Project Management system.

    Features include:

    • collaborate with your team and customers
    • plan tasks based on client requests
    • easily keep your budget in focus
    • send estimates and invoices
    • ticket and lead management
    • file sharing and messaging
    • and more

    This is another CMS and project management solution that includes lead management, a helpful feature, and makes it easy for clients to monitor and add feedback during the project.

    Zestpro - Project Management is solid CRM, especially for teams.

    10. FREELANCER PRO- Manage Your Work, Manage Your Life

    FREELANCER PRO- Manage Your Work, Manage Your Life was built on Laravel, PHP, and jQuery and attempts to bridge the gap between you and your clients.

    Included features:

    • export invoices to PDF, Excel, or send via email
    • unlimited clients, projects, tasks, tickets, etc.
    • easily follow task and project progress
    • fully responsive—works on the go
    • schedule invoices
    • generate reports
    • and more

    FREELANCER PRO- Manage Your Work, Manage Your Life takes a simple, straightforward approach to CRM and project management.

    Conclusion

    One thing that really stands out to me is how a good CRM and project management solution can be a huge asset. Not just an asset to me, as a freelancer, but something that I can offer to my clients.

    Have you considered hosting your own CRM and project management system? If not, I'm sure you're thinking about it now.

    What features do you find the most important?

    For more CRM and project management PHP scripts, take a look at Envato Market.

    3 days 4 hours ago

New Course: Instant Webpack 2

  • What You'll Be Creating

    The much-anticipated version 2 of the JavaScript module loader and bundler Webpack is now available, so why not learn all about it in our new course, Instant Webpack 2.

    In this course, instructor Dan Wellman will show you how to take a sample front-end web project and create a build system for it using Webpack. Topics include:

    • how to configure development and production builds
    • how to use plugins to transform the source code into bundles
    • how to handle common tasks like minification, caching, and code splitting
    • new features of Webpack, such as tree shaking and hot module replacement

    You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

    Plus you now get unlimited downloads from the huge Envato Elements library of 200,000+ photos and 26,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

     

    You can also find hundreds of useful JavaScript plugins on Envato Market to help your development work go more smoothly.

    3 days 6 hours ago

Sure, But Who's Gonna Pay to Colonize Space?

Verizon and WWE Data Exposures Come Down to Human Error

Space Photos of the Week: A Giant Molecular Cloud and All Its Star Bab

How the Guy Who Played Jar Jar Survived the Fandom Menace

Stromer ST1 X Review: This $5,000 Swiss Monster of an E-Bike Is Worth Every Euro

Pages