Anker launches new Thunderbolt 4 dock with 12 total ports

https://photos5.appleinsider.com/gallery/42899-83392-Apex-Thunderbolt-xl.jpg

Anker has launched a new Thunderbolt 4 dock that’s equipped with 12 total ports, including a 90-watt power pass-through slot and legacy options.

The Anker Apex Thunderbolt 4 dock sports the same general design as previous products in Anker’s work-from-home lineup, but sports a broader selection of ports.

Those ports include a 90W Thunderbolt 4 port that can power any M1 MacBook model, though it isn’t compatible with M1 desktops. There are also a pair of 4K HDMI ports, three USB-C ports, four USB-A ports, a Gigabit Ethernet port, a 3.5mm audio interface, and an SD card slot.

The Apex is compatible with a range of specifications, including USB4, DisplayPort, and PCI Express. The dock will be able to handle a single 8K display at 30Hz, a 4K display at 120Hz, or various other display combinations at 4K 60Hz. It can power up to three external monitors simultaneously, though only for Windows or Mac devices equipped with Intel chips.

Anker’s Apex Thunderbolt 4 dock is available for $299.99 at Amazon. It’s slated to start shipping on July 1.

Keep up with everything Apple in the weekly AppleInsider Podcast — and get a fast news update from AppleInsider Daily. Just say, “Hey, Siri,” to your HomePod mini and ask for these podcasts, and our latest HomeKit Insider episode too.

If you want an ad-free main AppleInsider Podcast experience, you can support the AppleInsider podcast by subscribing for $5 per month through Apple’s Podcasts app, or via Patreon if you prefer any other podcast player.

AppleInsider News

Using the Bridge Pattern in Laravel

https://ashallendesign.ams3.digitaloceanspaces.com/public/blog/23/using-the-strategy-pattern-in-laravel.png

Introduction

In software and web development, it’s always important to write code that is maintainable and extendable. The solution that you first create will likely change over time. So, you need to make sure you write your code in a way that doesn’t require a whole rewrite or refactor in the future.

The strategy pattern can be used to improve the extendability of your code and also improve the maintainability over time.

Intended Audience

This post is written for Laravel developers who have an understanding of how interfaces work and how to use them to decouple your code. If you’re a little unsure about this subject, check out my post from last week that discusses using interfaces to write better PHP code.

It’s also strongly advised that you have an understanding of dependency injection and how the Laravel service container works.

What Is the Strategy Pattern?

Refactoring Guru defines the strategy pattern as a “behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.”. This might sound a bit scary at first, but I promise that it’s not as bad as you think. If you want to read more into design patterns, I’d highly recommend checking out Refactoring Guru. They do a great job of explaining the strategy pattern in depth as well as other structural patterns.

The strategy pattern is basically a pattern that helps us to decouple our code and make it super extendable. In fact, you probably use it every day with Laravel without even noticing whenever you use the Storage and Cache facades (and a few other places too). Let’s say that you use this code:

Cache::put('name', 'Ash Allen', 600);

The code above is resolving a class from the service container by using the facade. I won’t get into how facades work as it’s not really the purpose of this article, but the important bit to know is that the Cache facade here is binding an interface (Illuminate\Contracts\Cache\Factory to be specific) to a class and using it. It is then storing the word ‘Ash Allen’ under the key ‘name’ for 10 minutes.

As you’ll have probably noticed in the Laravel documentation and in your project’s config, Laravel supports a few different drivers for caching, including: Redis, DynamoDB, Memcached and the database. So, for example, if we were to set our cache driver in our .env file to CACHE_DRIVER=redis, when we run our code snippet above, the data would be stored in our Redis cache. However, if we were to change the driver to be CACHE_DRIVER=database, this would result in data being stored in the database instead.

Each different cache driver has it’s own respective class that deals with how the framework interacts with the cache. So, when we change the driver in our .env, Laravel needs to know which driver to use. This is where the strategy pattern steps in. Under the hood, whenever we use the Cache facade, Laravel is actually resolving an Illuminate\Contracts\Cache\Factory interface from the service container. It does this by checking the config value (e.g. redis, database, etc.) and then mapping that interface to a class. For example, whenever we have our cache driver set to CACHE_DRIVER=redis and we try to resolve the Factory interface, we will get a class that specifically interacts with the Redis cache and nothing else.

As you can see, the strategy pattern can improve the extendability of your code. For example, if we wanted to create our own custom cache driver, we could just create the implementation and then let Laravel know that it is available for using. For a bit more context, check out the Laravel documentation to see an example of how you can add your own driver.

Using the Strategy Pattern in Laravel

Now that we have a basic idea of what the strategy pattern is, let’s look at how we can use it ourselves in our own Laravel application.

Let’s imagine that we have a Laravel application that users can use for getting exchange rates and currency conversions. Now, let’s say that our app uses an external API (exchangeratesapi.io) for getting the latest currency conversions.

We could create this class for interacting with the API:

class ExchangeRatesApiIO
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the exchangeratesapi.io API here and fetch the exchange rate.

        return $rate;
    }
}

Now, let’s use this class in a controller method so that we can return the exchange rate for a given currency. We’re going to use dependency injection to resolve the class from the container:

class RateController extends Controller
{
    public function __invoke(ExchangeRatesApiIO $exchangeRatesApiIO): JsonResponse
    {
        $rate = $exchangeRatesApiIO->getRate(
            request()->from,
            request()->to,
        );

        return response()->json(['rate' => $rate]);
    }
}

This code will work as expected, but we’ve tightly coupled the ExchangeRatesApiIO class to the controller method. This means that if we decide to migrate over to using a different API, such as Fixer, in the future, we’ll need to replace everywhere in the codebase that uses the ExchangeRatesApiIO class with our new class. As you can imagine, in large projects, this can be a slow and tedious task sometimes. So, to avoid this issue, instead of trying to instantiate a class in the controller method, we can use the strategy pattern to bind and resolve an interface instead.

Let’s start by creating a new ExchangeRatesService interface:

interface ExchangeRatesService
{
    public function getRate(string $from, string $to): float;
}

We can now update our ExchangeRatesApiIO class to implement this interface:

class ExchangeRatesApiIO implements ExchangeRatesService
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the exchangeratesapi.io API here and fetch the exchange rate.

        return $rate;
    }
}

Now that we’ve done that, we can update our controller method to inject the interface rather than the class:

class RateController extends Controller
{
    public function __invoke(ExchangeRatesService $exchangeRatesService): JsonResponse
    {
        $rate = $exchangeRatesService->getRate(
            request()->from,
            request()->to,
        );

        return response()->json(['rate' => $rate]);
    }
}

Of course, we can’t instantiate an interface; we want to instantiate the ExchangeRatesApiIO class. So, we need to tell Laravel what to do whenever we try and resolve the interface from the container. We can do this by using a service provider. Some people prefer to keep things like this inside their AppServiceProvider and keep all of their bindings in one place. However, I prefer to create a separate provider for each binding that I want to create. It’s purely down to personal preference and whatever you feel fits your workflow more. For this example, we’re going to create our own service provider.

Let’s create a new service provider using the Artisan command:

php artisan make:provider ExchangeRatesServiceProvider

We’ll then need to remember to register this service provider inside the app/config.php like below:

return [
    
    'providers' => [
        // ...
        \App\Providers\ExchangeRatesServiceProvider::class,
        // ...
    ],
	
]

Now, we can add our code to the service provider to bind the interfaces and class:

class ExchangeRatesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ExchangeRatesService::class, ExchangeRatesApiIO::class);
    }
}

Now that we’ve done all of this, when we dependency inject the ExchangeRatesService interface in our controller method, we’ll receive an ExchangeRatesApiIO class that we can use.

Taking It Further

Now that we know how to bind an interface to a class, let’s take things a bit further. Let’s imagine that we want to be able to decide whether to use the ExchangeRatesAPI.io or the Fixer.io API whenever we’d like just by updating a config field.

We don’t have a class yet for dealing with the Fixer.io API yet, so let’s create one and make sure that it implements the ExchangeRatesService interface:

class FixerIO implements ExchangeRatesService
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the Fixer API here and fetch the exchange rate.

        return $rate;
    }
}

We’ll now create a new field in our config/services.php file:

return [

    //...

    'exchange-rates-driver' => env('EXCHANGE_RATES_DRIVER'),

];

We can now update our service provider to change which class will be returned whenever we resolve the interface from the container:

class ExchangeRatesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ExchangeRatesService::class, function ($app) {
            if (config('services.exchange-rates-driver') === 'exchangeratesapiio') {
                return new ExchangeRatesApiIO();
            }
		  
            if (config('services.exchange-rates-driver') === 'fixerio') {
                return new FixerIO();
            }
		  
            throw new Exception('The exchange rates driver is invalid.');
        });
    }
}

Now if we set our exchanges rates driver in our .env to EXCHANGE_RATES_DRIVER=exchangeratesapiio and try to resolve the ExchangeRatesService from the container, we will receive an ExchangeRatesApiIO class. If we set our exchanges rates driver in our .env to EXCHANGE_RATES_DRIVER=fixerio and try to resolve the ExchangeRatesService from the container, we will receive an FixerIO class. If we set driver to anything else accidentally, an exception will be thrown to let us know that it’s incorrect.

Due to the fact that both of the classes implement the same interface, we can seamlessly change the EXCHANGE_RATES_DRIVER field in the .env file and not need to change any other code anywhere.

Conclusion

Is your brain fried yet? If it is, don’t worry! Personally, I found this topic pretty difficult to understand when I first learnt about it. I don’t think I started to really understand it until I put it into practice and used it myself. So, I’d advise spending a little bit of time experimenting with this yourself. Once you get comfortable with using it, I guarantee that you’ll start using it in your own projects.

Hopefully, this article has given you an overview of what the strategy pattern is and how you can use it in Laravel to improve the extendability and maintainability of your code.

If you found this post useful, I’d love to hear about it in the comments.

Keep on building awesome things! 🚀

Laravel News Links

Comic for June 27, 2021

https://assets.amuniversal.com/d165c9409a5601395f68005056a9545d

Thank you for voting.

Hmm. Something went wrong. We will take a look as soon as we can.

Dilbert Daily Strip

Screwing around at Lowes

I went to Lowes for more safety chain for the U-Haul trailer I’m pulling.

It comes with the DOT safety chain in case your hitch fails.

I wanted chain to padlock the trailer to the truck so it’s harder to steal the trailer by disconnecting it from the truck while it’s  parked.

So I ask for two 5-foot lengths of 5/16 trailer chain while holding some heavy duty padlocks.

The Lowes person and I have this conversation.

“What are you trying to secure?”

“I’m not”

“What’s the chain for?”

“Chain fights.”

“What?”

“Chain fights.  Two men enter, one man leaves.  You’ve never beat a man with a padlock on a chain? ”

“Umm….”

“It’s a hell of a rush.”

“Okay….”

“Chain fights.”

I’m gonna get banned from Lowes.

 

 

How Adhesive Bandages are Made

https://theawesomer.com/photos/2021/06/how_bandages_are_made_t.jpg

How Adhesive Bandages are Made

Link

Next time you get a cut and slap a bandage on it, remember this factory video in appreciation of all the engineering and operational complexity that goes into producing that little thing you stuck on your skin. There’s something incredibly satisfying about watching all of those roller machines running.

The Awesomer

Calling All Rebels! CMMG Drops Secret Plans to Build Your Own AR Blaster!

https://cdn0.thetruthaboutguns.com/wp-content/uploads/2021/06/build_blaster.jpegCalling All Rebels! CMMG Drops Secret Plans to Build Your Own AR Blaster!

CMMG has brought a piece of cinematic history to life by pulling together the parts and plans to build an AR Blaster in 22LR.

Check out the interactive video below to view all the parts needed to build your own AR Blaster!

 

 

 

 

Continue reading Calling All Rebels! CMMG Drops Secret Plans to Build Your Own AR Blaster! at The Truth About Guns.

The Truth About Guns

Recall Notice: Winchester and Browning 9mm Ammo

https://www.thefirearmblog.com/blog/wp-content/uploads/2021/06/re-180×180.jpg

Certain lots of Winchester and Browning 115gr 9mm ammo have been recalled for safety.When it comes to handling your firearms in any capacity or context, nothing is more important than safety. Everyone should know the basic firearms safety rules inside and out before they ever get on a live-fire range. Beyond those fundamentals like keeping your gun pointed in a safe direction and keeping your finger off of […]

Read More …

The post Recall Notice: Winchester and Browning 9mm Ammo appeared first on The Firearm Blog.

The Firearm Blog

New Device Creates Water From Thin Air

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/b1252a9e16958b923f134c4172466771.jpg

The pilot condenser atop an ETH Zurich building.
Photo: ETH Zurich/Iwan Hächler

As we look towards a Waterworld-esque future where our access to H20 is increasingly rare, it’s even more important to figure out how to squeeze every last drop we can, including out of thin air. In a study published Wednesday in Science Advances, a team of researchers from ETH Zurich demonstrated a new way to create drinking water from humidity using only the sun as power.

There are lots of powerful atmospheric water generators on the market. But they still rely on technologies like fans that need external power. Passive water collection systems, meanwhile, are time-limited: They generally only work at night, when humidity is higher, and the water is in danger of evaporating back into the atmosphere when the sun comes up. There’s been a recent surge in techniques that use trays of materials, like gels, metals, salts, and other compounds to collect water when humidity is high at night; the material is then naturally heated by the sun and releases the water it has collected. The downside of this technique, however, is that it’s not 24/7, and it’s not automatic. The team of researchers wanted to bypass all these systems’ various issues.

“We said, let’s try something that really doesn’t require any energy, so it’s really energy neutral and only limited by physical principles,” said Iwan Hächler, a postdoctoral fellow at ETH Zurich and the lead author of the study. “We thought, ‘what if we show we can evaporate water? What if we try to condense it using radiative heat or radiative energy?’”

The resulting design is deceptively simple–it looks basically like a wide cone placed on top of a box, with a glass pane at the narrow end of the cone on top of the box. Each component here plays a key role.

Condensation happens when water in the air comes in contact with a surface that is below the ambient temperature. To ensure this process happens, researchers coated the glass pane with polymer and silver, allowing it to reflect the sunlight back and keep itself cooler than the ambient temperature. On the underside of the pane is a special coating where moisture from the air can collect and drop without requiring human or mechanical help. The cone acts like a radiation shield, which keeps the device from overheating and deflects the heat energy created from the condensation process.

G/O Media may get a commission

“True condensation creates a tremendous amount of heat, because of the phase change of the water from gaseous to liquid,” said Hächler. “So we designed a radiation shield, which boosted the performance to allow us to get bigger yields.”

The design works pretty well, Hächler said. In lab tests, the maximum yield his team was able to get from the device was 0.05 liters (1.8 fluid ounces) per square meter per hour, very close to the theoretical maximum yield that researchers had calculated. That means the device is able to practically produce around 1.2 liters per square meter per day, or about a third of a person’s required daily intake. This is around twice the output of other passive technologies, the researchers said.

One of the biggest pluses of this system is that it is pretty easy and cheap to set up. Hächler said that the special coating that eliminates the water-wiping action isn’t totally needed to make the system function, while the silver coating on the glass pane would probably work just as well with any super-reflective surface, like chalk or white paint.

“We made a joke that we should make a version with cardboard and aluminum, but we could,” said Gabriel Schnoering, a professor of thermodynamics at ETF Zurich and another coauthor of the study. “Maybe not the same performance, but the idea works with glass, cardboard, aluminum.”

The possibilities for a device that could just sit there and create water for days on end are, pretty big. The climate crisis is causing dry places to become even drier. In other locations, groundwater reserves are being depleted at an unsustainable level. While the system alone couldn’t meet the needs of a region like the entire western U.S., which is currently in a megadrought and facing water restrictions, it could still play a role in helping address shortages there or other parts of the world that are water stressed.

Hächler said the system could be easily coupled with desalination. The air near the surface of the ocean is pretty humid, so desalination systems “could just let [the device] float around” and do its job. And it opens up possibilities for people living in poorer or remote areas without steady power who need more water.

“You could imagine installing it on a roof for families, and they could get some potable water,” he said.

Gizmodo