Git Product home page Git Product logo

generators's Introduction

Laravel File Generators

Custom Laravel File Generators with a config file and publishable stubs. You can publish the stubs. You can add your own stubs to generate.

This package is being used in Admin Starter Project that focuses on test driven development and has the foundation ready for you.

Laravel 5.1 : v2.1.3
Laravel 5.2 - 5.3 : v3.0.3
Laravel 5.4 : v4.1.9
Laravel 5.5 - 5.8 : v5.0.0+
Laravel 6.0 : v5.1.0+
Laravel 7.0 : v6.x
Laravel 8.0 : v7.x
Laravel 9.0 : v8.x
Laravel 10.0 : v9.x

Commands

php artisan generate:publish-stubs
php artisan generate:model
php artisan generate:view
php artisan generate:controller
php artisan generate:migration
php artisan generate:migration:pivot
php artisan generate:seed
php artisan generate:resource
php artisan generate:repository
php artisan generate:contract
php artisan generate:notification
php artisan generate:event
php artisan generate:listener
php artisan generate:event-listener
php artisan generate:trait
php artisan generate:job
php artisan generate:console
php artisan generate:middleware
php artisan generate:factory
php artisan generate:test
php artisan generate:file
php artisan generate:exception
php artisan generate:component
php artisan generate:livewire

Option for all the commands

  • --force This will override the existing file, if it exists.
  • --test This will also generate a test file.

Option for all the commands, except views and migration:pivot

  • --plain This will use the .plain stub of the command (generate an empty controller)

Customization

This is for all except the migration and migration:pivot commands

php artisan generate:file foo.bar --type=controller
php artisan generate:view foo.bar --stub=view_show --name=baz_show
php artisan generate:file foo.bar --type=controller --stub=controller_custom --name=BazzzController --plain --force

You can specify a custom name of the file to be generated. You can add the --plain or --force options. You can override the default stub to be used. You can create your own stubs with the available placeholders. You can create new settings' types, for example:

  • 'exception' => ['namespace' => '\Exceptions', 'path' => './app/Exceptions/', 'postfix' => 'Exception'],

Available placeholders

Views Custom Stubs

php artisan generate:view posts
php artisan generate:view admin.posts --stub=custom
php artisan generate:view admin.posts --stub=another_file

Installation

Update your project's composer.json file.

composer require bpocallaghan/generators --dev

Add the Service Provider (Laravel 5.5+ has automatic discovery of packages) You'll only want to use these generators for local development, add the provider in app/Providers/AppServiceProvider.php:

public function register()
{
    if ($this->app->environment() == 'local') {
        $this->app->register(\Bpocallaghan\Generators\GeneratorsServiceProvider::class);
    }
}

Run php artisan command to see the new commands in the generate:* section

Usage

Models

php artisan generate:model bar
php artisan generate:model foo.bar --plain
php artisan generate:model bar --force
php artisan generate:model bar --factory
php artisan generate:model bar --migration
php artisan generate:model bar --migration --schema="title:string, body:text"

Views

php artisan generate:view foo
php artisan generate:view foo.bar
php artisan generate:view foo.bar --stub=view_show
php artisan generate:view foo.bar --name=foo_bar

Controllers

php artisan generate:controller foo
php artisan generate:controller foo.bar
php artisan generate:controller fooBar
php artisan generate:controller bar --plain
php artisan generate:controller BarController --plain
  • The Controller postfix will be added if needed.

Migrations

This is very similar as Jeffrey Way's

php artisan generate:migration create_users_table
php artisan generate:migration create_users_table --plain
php artisan generate:migration create_users_table --force
php artisan generate:migration create_posts_table --schema="title:string, body:text, slug:string:unique, published_at:date"

Pivot Tables

This is very similar as Jeffrey Way's

php artisan generate:migration:pivot tags posts

Database Seeders

php artisan generate:seed bar
php artisan generate:seed BarTableSeeder
  • The TableSeeder suffix will be added if needed.

Resource

php artisan generate:resource bar
php artisan generate:resource foo.bar
php artisan generate:resource foo.bar_baz
php artisan generate:resource bar --schema="title:string, body:text, slug:string:unique, published_at:date"
php artisan generate:resource articles --controller=admin
  • This will generate a Bar model, BarsController, resources views (in config), create_bars_table migration, BarTableSeeder
  • In the config there is a resource_views array, you can specify the views that you want to generate there, just make sure the stub exist.
  • This will also ask you to generate the 'repository - contract pattern' files.
  • The --controller=admin allows you to use the controller_admin stub when generating the controller.

Repository

php artisan generate:repository Posts

This will generate a Posts Repository file to be used in your controller.

Contract

php artisan generate:contract Cache

This will generate a Cache Contract file to be used with your repositories.

Notifications

php artisan generate:notification UserRegistered

This will generate a UserRegistered notification. Laravel provides support for sending notifications across a variety of delivery channels, including mail, SMS (via Nexmo), and Slack. Notifications may also be stored in a database so they may be displayed in your web interface.

Events and Listeners

php artisan generate:event InvoiceWasPaid
php artisan generate:listener NotifyUserAboutPayment --event=InvoiceWasPaid
php artisan generate:event-listener

This will generate the event and listener. Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application

php artisan generate:event-listener Will generate all the missing events and listeners defined in your EventServiceProvider.

Trait

php artisan generate:trait Http\Controllers\Traits\Bar

This will generate a FooBar Trait file. The command will use the name as your namespace. generate:trait Foo will create a file in app/Foo.php, generate:trait Foo\Bar will create a file in app/Foo/Bar.php.

Job

php artisan generate:job SendReminderEmail

This will generate a SendReminderEmail Job file.

Console (Artisan Command)

php artisan generate:console SendEmails
php artisan generate:console SendEmails --command=send:emails

This will generate a SendEmails Artisan Command file. The --command option is optional.

Middleware

php artisan generate:middleware AuthenticateAdmin

This will generate an AuthenticateAdmin Middleware file.

Factory

php artisan generate:factory Post
php artisan generate:factory PostFactory

This will generate a PostFactory model file.

Test

php artisan generate:test UserCanLogin
php artisan generate:test Post --unit
php artisan generate:test Auth\LoginTest

This will generate Feature\UserCanLogin and Unit\PostTest and Unit\Auth\LoginTest files.

Component

php artisan generate:component Foo
php artisan generate:component Foo/Bar
php artisan generate:component Baz --test

This will generate a Laravel Component. The php and blade files will be generated. You can also specify to generate a unit test.

Livewire

php artisan generate:livewire Foo
php artisan generate:livewire Foo/Bar
php artisan generate:livewire Baz --test
php artisan generate:livewire foo-bar --request

This will generate a Livewire component. The php and blade files will be generated. You can also specify to generate a test or a form request.

Configuration

php artisan generate:publish-stubs

This will copy the config file to /config/generators.php. Here you can change the defaults for the settings of each type, like model, view, controller, seed. You can also change the namespace, path where to create the file, the pre/post fix, and more. You can also add new stubs.

This will also copy all the stubs to /resources/stubs/. Here you can make changes to the current stubs, add your own boilerplate / comments to the files. You can also add your own stubs here and specify it in the config to be used. Migration Stub Note: The migration.stub is only the outer part and the schema_create.stub or schema_change.stub is where you modify the schema itself. The schema_create.stub has boilerplate added to it.

File

This is the base command for the view, model, controller, seed commands. The migration and migration:pivot uses Jeffrey's classes. In the config there is a settings array, this is the 'types' and their settings. You can add more, for example, if you use repositories, you can add it here.

php artisan generate:file foo.bar --type=view
php artisan generate:file foo.bar --type=controller
php artisan generate:file foo.bar --type=model
php artisan generate:file foo.bar --type=model --stub=model_custom

Customizing file was created message to add support for ide opening the files

Make links for opening output. Add output_path_handler as a function to your config/generators.php.Example:

'output_path_handler' => static function($path){
    return 'file:///' . base_path() . $path;
},

This will output a file schema uri which JetBrain Products (Intellij,Php Storm,Web Storm,...) then can open directly from your terminal.

Thank you

My Other Packages

  • Alert A helper package to flash a bootstrap alert to the browser via a Facade or a helper function.
  • Notify Laravel Flash Notifications with icons and animations and with a timeout
  • Impersonate User This allows you to authenticate as any of your customers.
  • Sluggable Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model.

generators's People

Contributors

bpocallaghan avatar markcameron avatar stevemoretz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

generators's Issues

generate pivot table missing Name

Ex:

When I run the generate:migration:pivot foos bars

The migration created is created as:

class extends Migration
{

(missing the name)

I believe it should be

class CreateFooBarPivotTable extends Migration
{

I don't see that this function is being called anywhere during the pivot migration

protected function parseName($name)
{
$tables = array_map('str_singular', $this->getSortedTableNames());
$name = implode('', array_map('ucwords', $tables));

    return "Create{$name}PivotTable";
}

From the:
public function fire()
{
$name = $this->qualifyClass($this->getNameInput());
......

It looks like it is calling only
/**
* Empty 'name' argument
*
* @return string
*/
protected function getNameInput()
{
//
}

Which of course will return an empty name

In the meantime, I'll just type that in

Thanks

PHP 8 Compat

Hi,

It looks like this package is locked to PHP 7:

- bpocallaghan/generators is locked to version 7.0.1 and an update of this package was not requested.
- bpocallaghan/generators 7.0.1 requires php ^7.3 -> your php version (8.0.3) does not satisfy that requirement.

Consistency in {{resource_name}} in Controllers

Love the package...using it daily.

However, in using:

generate:resource example_resource

In the controller section, it is not consistent with the others like view, model, etc...

It changes the {{resource_name}} to {{resourceName}}

I commented out the code here:

private function callController()
{
$name = $this->getResourceControllerName();
if ($this->confirm("Create a controller ($name) for the $this->resource resource? [yes|no]")) {
$arg = $this->getArgumentResource();
$name = substr_replace($arg, str_plural($this->resource), strrpos($arg, $this->resource), strlen($this->resource));
// foo.bar_baz == foo.barBaz
//$pieces = explode('_', $name);
//$name = "";
//foreach ($pieces as $k => $str) {
// $name .= ucfirst($str);
//}
$this->callCommandFile('controller', $name);
}
}

Now works as expected, unless I am missing why we would go fooBar instead of foo_bar when we use:
php artisan generate:resource foo_bar

Of course the model being FooBar is understandable...but when we call {{resource_name}} in the other sections...it gives foo_bar as expected.

Thanks for the hard work!

Erik

Migration is auto populated with personal preferences.

Using this command :

php artisan generate:model bar --migration --plain

It created a migration with this up method :

  public function up()
    {
        Schema::create('bars', function (Blueprint $table) {
            $table->bigIncrements('id')->unique()->index();
            
            $table->timestamps();
            $table->softDeletes();
            $table->integer('created_by')->unsigned();
            $table->integer('updated_by')->unsigned()->nullable();
            $table->integer('deleted_by')->unsigned()->nullable();
        });
    }

I don't want these auto generated fields from out of nowhere to come they were not in the stub file as well.

Inject methods into models during generate:migration:pivot foo bar

Not an issue, but would be helpful.

During this process would it make sense to automatically establish the many-to-many relationship between foo and bar put

In the Bar model:

public function foos() {
return $this->(Belongs to many stuff here with the 4 parameters)
}

In the Foo model

public function bars(){
return $this->belongsToMany( inverse of above not needing the 4 parameters??)
}

Thoughts?

Config and publishing stubs

I can't publish the config file using php artisan vendor:publish, nor does it publish the stubs. Is there specific way of doing this, or will you implement the publishes() method in the service provider to automatically export them?

Thanks

Add a FileCommand

Maybe add a FileCommand that will take a --stub option for the name of the stub to use from the config file.
So that you will be able to generate any file you add in the config file.
Generate any custom files, that will be able to use all the placeholders available.

Composer Update doesn't recognize existing stubs

Hey Ben-Piet!

It's been awhile, I saw the update so I ran it...

However, if stubs are already published, they need to be published again with --force in order for them to be used...I just cleaned in git all my existing stubs, then it worked...

Abstract the placeholders used in BuildClass method

Add a protected function for the placeholders used in the build method.
So that each generate command uses the same logic to generate placeholders, and each generate command has access to all the placeholders available.

generate:migration:pivot has inverted classes

When we use this command and inject the many to many relationship in the model, the classes are inverted.

Example

generate:migration:pivot bar foo

would currently add in the Foo Class Model

public function bars()
{
return $this->belongsToMany(Foo::class);
}

I believe it should be

public function bars()
{
return $this->belongsToMany(Bar::class);
}

Validator idea

Validator idea...
Also, I never run the migration at the time of generate:resource since there are only a few things that are common, the rest gets built, then the migration is performed. Once performed, it would be great to do some like:

generate:validator foo_bar

And then using Doctrine/dbal we could get the schema and inject the proper validator in the store and update of the FooBarController (at least all of the required fields.)

Migration - Add placeholders

In {{schema_up}}...{{resource_name}} is not pulling in and shows up as "{{resource_name}}" so if we have a resource of foo_bars...in my stub for the migration we have
$table->string('{{resource_name}}_name');

It would be nice to have it come in as
$table->string('foo_bar_name');

MigrationCommand - use the base FileCommand - to get access to all the 'placeholders' to replace in the stub.

Some feature request and speaking of generate::request

Hi,
I was thinking about what you've done here.You know that message that says

.somepath/some/test.bladee.php Was generated
At the end.I guess it could be great if in config/generator.php

A function could be defined to handle that message.

You may think what kind of stupid feature is that :D

But the purpose is that you can do a few stuff here to open the files that were generated in the ide.

Since I think it isn't such a great idea to handle all these ide opening stuff yourself because I see you're working alone on this, I guess that would be a lot better so you can do a few ones and let the rest of it to the other ide users.

There are two possible ways to open a file in ide from php.

Either output a link like idea://blahblah...
Which is a link that when opens gets you there.
Or some ideas again like intellij suppert a command for opening files in terminal so a exec() in php could do that or again intellij can open files in this link too : file:///path.blade.php

So you get the point,that could let the users do any of these ways in their ides which I think is a great idea.


The other thing you said generate::request

I don't know what that is but in a few days I'm making something which basically makes adding somethings like routes in web.php automated from php well essentially I'm doing it for some other reason, but if that's something like what you need, I'll provide the code to what I've done when it's done and also can help you adapt it for your own use case.It's just a little playing with regex. But I guess you won't need my help. Anyways it never hurts to hear somebody offers some help.

Enhancement for repositories/contracts

Would it be possible to also add stubs for repositories and contracts?

Our project is growing and it would be nice to stub out this when we use generate:resource foo and maybe add flags to include a repository and contract?

What do you think?

We also came across the quasar framework

Totally Vue..pretty nice...thought I would share.

http://quasar-framework.org

Trait 'Illuminate\Console\DetectsApplicationNamespace' not found in Laravel 5.3

Hello,

I just noted this issue, you might be aware but still just mentioning here.

Class ListenerCommand, FileCommand which use the 'DetectsApplicationNamespace' trait which is present only after 5.4. So please either add minimum Laravel version in a composer.json & readme.md or use AppNamespaceDetectorTrait for an older version.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.