技術情報

PHP Zipper package using PHP ZipArchive

Today I would like to share a PHP package that I wrote last weekend. This was written to make Zipping processes easily and automatically using PHP ZipArchive. Let’s take a look.

First of all, install the package with composer.

composer require waithaw/phpzipper

After creating Zip Object, you can use the following methods.

include_once "vendor/autoload.php";

use WaiThaw\PhpZipper\Zip;

$zip = new Zip();


These are the example file lists.

$filelists= [
    'D:\testfolder\test1.txt',
    'D:\testfolder\test1folder\test2.txt'
];

$file = 'D:\testfolder\test1.txt';

Creating a Zip file from Single file or multiple files

You can create an archive zip file from single file or multiple files.

1st parameter – output zip path

2nd parameter – a file or files to be zipped

3rd parameter – setting a password

  • Zipping a single file or mutiple files with no password

$zip->createFromFiles('backup.zip', $file);

//OR

$zip->createFromFiles('backup.zip', $filelists);


  • Zipping a single file or mutiple files with password

$zip->createFromFiles('backup.zip', $file ,'password');

//OR

$zip->createFromFiles('backup.zip', $filelists,'password');


Creating a Zip file from a directory including sub directories.

You can archive all files and subfolders in a directory into a zip file.

  • Zipping a directory with no password

$zip->createFromDir('backup.zip','D:\testfolder');

  • Zipping a directory with password

$zip->createFromDir('backup.zip','D:\testfolder','password');

Extracting a simple or password-protected zip file

  • Extracting a simple zip file.

$zip->extractTo('backup.zip','D:\outputpath');

  • Extracting a password-protected zip file

$zip->extractTo('backup.zip','D:\outputpath', 'password');

Downloading zip files

You can download the zip file at once archiving.

$zip->createFromFiles('backup.zip', $file)->download();

$zip>createFromDir('backup.zip','D:\testfolder')->download();


And you can also delete the zip file after downloaded, by passing ‘delete’ string in download() method.

$zip->createFromFiles('backup.zip', $file)->download('delete');

$zip>createFromDir('backup.zip','D:\testfolder')->download('delete');


This is all for now. I will continue to update this package for more features and details.

Hope you enjoy that.

By Asahi



Tips & best practices for Laravel 8

This article will show you the mysterious tricks that might help you when writing code with Laravel.

1.Use local scopes when you need to query things

Laravel has a nice way to write queries for your database driver using Query Builder. Something like this:

$orders = Order::where(‘status’, ‘delivered’)->where(‘paid’, true)->get();

This is pretty nice.But this bit of code can be better written if we use local scopes.

Local scopes allow us to create our Query Builder methods we can chain when we try to retrieve data. For example, instead of ->where() statements, we can use ->delivered() and ->paid() in a cleaner way.

First, in our Order model, we should add some methods:

class Order extends Model
{
...
public function scopeDelivered($query) {
return $query->where('status', 'delivered');
} public function scopePaid($query) {
return $query->where('paid', true);
}
}

When declaring local scopes, you should use the scope[Something] exact naming. In this way, Laravel will know that this is a scope and will make use of it in your Query Builder. Make sure you include the first argument that is automatically injected by Laravel and is the query builder instance.

$orders = Order::delivered()->paid()->get();

For more dynamic retrieval, you can use dynamic local scopes. Each scope allows you to give parameters.

class Order extends Model
{
...
public function scopeStatus($query, string $status) {
return $query->where('status', $status);
}
}$orders = Order::status('delivered')->paid()->get();

Laravel uses by default where[Something] to replace the previous scope. So instead of the previous one, you can do:

Order::whereStatus(‘delivered’)->paid()->get();

Laravel will search for the snake_case version of Something from where[Something]. If you have status in your DB, you will use the previous example. If you have shipping_status, you can use:

Order::whereShippingStatus(‘delivered’)->paid()->get();

2.Magic scopes

When building things, you can use the magic scopes that are already embedded

  • Retrieve the results by created_at , descending:
           User::latest()->get();
  • Retrieve the results by any field, descending:
           User::latest('last_login_at')->get();
  • Retrieve results in random order:
           User::inRandomOrder()->get();
  • Run a query method only if something’s true:

3.Do not store model-related static data in configs

Instead of this:

BettingOdds.php

class BettingOdds extends Model
{
   ...
}

config/bettingOdds.php

return [
   'sports' => [
      'soccer' => 'sport:1',
      'tennis' => 'sport:2',
      'basketball' => 'sport:3',
      ...
   ],
];

And accessing them using:

config(’bettingOdds.sports.soccer’);

I prefer doing this:

BettingOdds.php

class BettingOdds extends Model
{
protected static $sports = [
'soccer' => 'sport:1',
'tennis' => 'sport:2',
'basketball' => 'sport:3',
...
];
}

And access them using:

BettingOdds::$sports['soccer'];

Because it’s easier to be used in further operations:

class BettingOdds extends Model
{
protected static $sports = [
'soccer' => 'sport:1',
'tennis' => 'sport:2',
'basketball' => 'sport:3',
...
];public function scopeSport($query, string $sport)
{
if (! isset(self::$sports[$sport])) {
return $query;
}

return $query->where('sport_id', self::$sports[$sport]);
}
}

Now we can enjoy scopes:

BettingOdds::sport('soccer')->get();

4.Use collections instead of raw-array processing

Back in the days, we were used to working with arrays in a raw way:

$fruits = ['apple', 'pear', 'banana', 'strawberry'];foreach ($fruits as $fruit) {
echo 'I have '. $fruit;
}

Now, we can use advanced methods that will help us process the data within arrays. We can filter, transform, iterate and modify data inside an array:

$fruits = collect($fruits);$fruits = $fruits->reject(function ($fruit) {
return $fruit === 'apple';
})->toArray();['pear', 'banana', 'strawberry']

Tsuki





JavaScriptでQRコードをスキャンする

今回はJavaScriptでQRコードをスキャンするライブラリcozmo/jsQR(https://github.com/cozmo/jsQR)を紹介します。

前回の記事「PHP QRコード生成ライブラリ「endroid/qr-code」」ではQRコードの生成方法を紹介しましたが、今回は生成したQRコードをスマートフォンやPCのWebカメラを使用してJavaScriptでスキャンする方法を紹介いたします。

続きを読む

Different Laravel methods firstOrNew, firstOrCreate, firstOr, and updateOrCreate

Standard methods for creating Eloquent Models like make()create()update, and save(). Laravel includes some other methods are that also really useful for creating and updating Models that I feel don’t get enough attention. So in this article, I’d like to go over some of these additional methods and explain how they might be useful.

1. firstOrNew

The firstOrNew method is really useful for finding the first Model that matches some constraints or making a new one if there isn’t one that matches those constraints.

You can take a piece of code that looks like this:

$user = User::where(‘email,’$request->email)->first();

if($user === null){

$user = new User([ ‘email’ => $request->email ]);

$user->name = $request->name;

$user->save();

}

And turn it into this:

$user = User::firstOrNew( [ ‘email’ => $request->email ] );

$user->name = $request->name;

$user->save();

You may also pass an array of additional attributes to set as the second parameter if no existing Model is found:

$user = User::firstOrNew([‘email’ => request(‘email’)],[‘name’ => request(‘name’)]);

$user->save();

2.firstOrCreate

I recently found the firstOr method while source-diving. The firstOr method retrieves the first Model from a query, or if no matching Model is found, it will call a callback passed. This can be really useful if you need to perform extra steps when creating a user or want to do something other than creating a new user:

$user = User::where(‘email,’$request->email)->firstOr(function(){

$account = Account::create([

return User::create([

‘account_id’ => $account->id,

‘email’ => $request->email

]);

]);

});

3.firstOr

I recently found the firstOr method while source-diving. The firstOr method retrieves the first Model from a query, or if no matching Model is found, it will call a callback passed. This can be really useful if you need to perform extra steps when creating a user or want to do something other than creating a new user:

$user = User::where(‘email,’$request->email)->firstOr(function(){

$account = Account::create([

return User::create([

‘account_id’ => $account->id,

‘email’ => $request->email

]);

]);

});

4.updateOrCreate

The updateOrCreate method attempts to find a Model matching the constraints passed as the first parameter. If a matching Model is found, it will update the match with the attributes passed as the second parameter. If no matching Model is found a new Model will be created with both the constraints passed as the first parameter and the attributes passed as the second parameter.

You can refactor this piece of code:

$user = User::where(‘email,’$request->email)->first();

if($user !== null){

$user->update([‘name’ => $request->name]);

}else{

$user = User::create([

‘email’ => $request->email,

‘name’ => $request->name

]);

}

To this using the updateOrCreate method:

$user = User::updateOrCreate([

‘email’ => $request->email,

‘name’ => $request->name

]);

Tsuki



The 10 best new features in Laravel 8

1. app/Models Directory

The artisan:make model command will create the model in the app/Models directory. This feature was decided after Taylor asked people on Twitter how they feel about this.

If you don’t like that, it’s possible to delete the app/Models directory and artisan will create the model file in the app/ folder. 

2. New Landing Page

Laravel 8 comes with a new landing page for a brand new install. It is now redesigned and It is built using TailwindCSS, includes light and dark-mode capabilities, and by default extends links to SaaS products and community sites.

3. Controllers Routing Namespacing

No more double prefix issues! In previous versions of Laravel, the RouteServiceProvider had an attribute called namespace that was used to prefix the controllers in the routes files. That created a problem when you were trying to use a callable syntax on your controllers, causing Laravel to mistakenly double prefix it for you. This attribute was removed and now you can import and use it without the issue.

It can also be used for single action controllers that have the __invoke method.

Route::get(‘/welcome’, [WelcomeController::class, ‘index’]);

Route::get(‘/welcome’, WelcomeController::class);

4. Route Caching

Laravel uses route caching to compile your routes in a PHP array that is more efficient to deal with. In Laravel 8, it’s possible to use this feature even if you have closures as actions to your routes. This should extend the usage of route caching for improved performance.

Route::get(‘/components’, function(){

return view(‘button’);

});

5. Attributes on Extended Blade Components

In Laravel 7 the child components didn’t have access to the $attributes passed to it. In Laravel 8 these components were enhanced and it is now possible to merge nested component attributes. This makes it easier to create extended components.

6. Better Syntax for Event Listening

In the previous versions of Laravel, when creating a closure-based event listener there was much repetition and a cumbersome syntax.

Event::listen(ConferenceScheduled::class, function( ConferenceScheduled $event){

info(get_class($event));

});

In Laravel 8 it’s simpler and cleaner:

Event::listen(function( ConferenceScheduled $event){

info(get_class($event));

});

//one line version

Event::listen(fn( ConferenceScheduled $event =>info(get_class($event))));

7. Queueable Anonymous Event Listeners

In Laravel 8 it is possible to create queueable closure from anywhere in the code. This will create a queue of anonymous event listeners that will get executed in the background. This feature makes it easier to do this, while in previous versions of Laravel you would need to use an event class and an event listener (using the ShouldQueue trait).

<?php

namespace App\Models;

use function Illuminate\Events\queueable;

Class User extends Authenticable

{

protected static function booting()

{

static::created( queueable ( function (User $user) {

info(‘ Queued: ‘.$user->name);

});

}

}

8. Maintenance Mode

artisan downsecret=laracon-2020

This is especially useful when you need to do some maintenance on your application and you want to take it down for your users but still let your developers investigate bugs. This will create a secret cookie that will be granted to whoever hits the correct endpoint, allowing it to use the application while in maintenance mode.

artisan down –render=”errors:503″

Pre-rendering an error view is a safe way for not exposing errors to your end user when your application is down (during a new deployment, for example). The Laravel 8 framework guarantees that your predefined error page will be displayed before everything else from the application.

artisan down –render=”welcome” –redirect=/ –status=200 –secret=laracon-2020

This combines the new features and will make the application only display a single predefined route, while still allowing for the people who have the secret to test and debug. This can be very useful when launching a new app.

9. Closure Dispatch “Catch”

Route::get(‘/queue-catch’, function(){

dispatch( function() {

throw new Exception(‘Something went wrong…’);

})->catch(function( Throwable $e){

info(‘Caught exception!!’);

})

});

Laravel has a pretty robust queue system that accepts a closure queue that will get serialized and executed in the background. Now we have a way to handle failures in case your job fails.

10. Exponential Backoff Strategy

This is an algorithm that decreases the rate of your job in order to gradually find an acceptable rate.

public function backoff(){

return [1,5,10];

}

Tsuki




アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム