Blacksmith is a code generation tool which automates the creation of common files that you'd typically create for each entity in your application.

Related tags

Laravel blacksmith
Overview

Blacksmith

Blacksmith is a code generation tool which automates the creation of common files that you'd typically create for each entity in your application.

Blacksmith works nicely with the Laravel PHP framework but does not actually depend on Laravel or extend an Artisan task, it is stand alone. This allows you to use it for code generation from a template anywhere on your filesystem. In fact, while some of the generator specific template variables and post-generation tasks of the Intelligent Laravel Generators are Laravel specific; if the code you want to generate uses studly case and snake case naming, you could generate any code you wanted: Java, JavaScript etc.


Build Status Code Coverage Scrutinizer Code Quality

Out of the box for the 1.0.0 release Blacksmith ships with a Laravel hexagonal architecture configuration and templates. Why? Because this is what I needed first.

Note: If you want to get started with the hexagonal architecture referenced above for a new app. Use Foreman with this example config (changing the 'from' paths appropriatley).

If you don't like the templates + configuration shipped with Blacksmith, don't worry you can make your own custom templates tell Blacksmith how to load them with a JSON config file. Then you just pass that config file's path as an optional argument to Blacksmith's generate command and presto, your custom templates and config are used.

Attribution: Blacksmith was inspired by, and even borrows some code from Jeffrey Way's fantastic MIT licensed Laravel-4-Generators package

README Contents

## What does it do

Out of the box Blacksmith ships with the following generators:

Single Generators (generates one file)

  • model
  • controller
  • seed
  • migration_create
  • view_create
  • view_update
  • view_show
  • view_index
  • form
  • test_unit
  • test_functional
  • service_creator
  • service_updater
  • service_destroyer
  • validator

Aggregate Generators (calls 1 or more other generators)

  • scaffold - calls all generators above with the given arguments
## Installation ### Download the PHAR The simplest method of installation is to simply [download the blacksmith.phar](https://github.com/indatus/blacksmith/raw/master/blacksmith.phar) file from this repository. > **(Optional) Move and set permissions** Now if you'd like you can move the PHAR to `/usr/local/bin` and rename it to `blacksmith` for easy access. You may need to grant the file execution privileges (`chmod +x`) before running commands. ### Compile from source To compile the blacksmith.phar file yourself, clone this repository and run the `box build` command. To run box commands, you must install [kherge/Box](https://github.com/kherge/Box).

See optional move and permissions above.

### Updating Blacksmith

To update Blacksmith, you may use the blacksmith self-update command.

## Usage

Blacksmith generation commands have the following signature:

blacksmith generate {entity} {generator} [config_file] --fields="field1:type, field2:type"

In the example above the config_file argument and --fields option are both optional. {entity} is the name of the entity in your use case that you are generating code for, and {generator} is the generator you want to run.

To declare fields, use a comma-separated list of key:value:option sets, where key is the name of the field, value is the column type, and option is a way to specify indexes or other things like unique or nullable. Here are some examples:

  • --fields="first:string, last:string"
  • --fields="age:integer, yob:date"
  • --fields="username:string:unique, age:integer:nullable"
  • --fields="name:string:default('John'), email:string:unique:nullable"
  • --fields="username:string[30]:unique, age:integer:nullable"

Please make note of the last example, where we specify a character limit: string[30]. This will produce $table->string('username', 30)->unique();

An example without placeholders might look like this:

blacksmith generate User scaffold ~/blksmth/cfg.json --fields="username:string:unique, age:integer:nullable"

Note: Blacksmith works from your current working directory, so if you have a template that gets written to a releative path, that will be relative to your current directory when you run Blacksmith. For Laravel this directory should be the application root.

## Getting Started

While Blacksmith comes packaged with templates and base configuration file, it's likely you'll want to download the templates and customize them to suit your needs. This will also require you create your own config file which you can read more about in the Config File section.

As you begin to generate you may notice some interfaces and classes referenced in templates that were not generated. This is not a mistake. Any classes you only create one time are not generated by Blacksmith and can be obtained from Blacksmith-contracts.

## The Config File

The Blacksmith config file is written in JSON and has a specific format. Blacksmith will validate the file's format before use and provide errors if there is a mis-configuration.

The config file has a root level item for each single generator, and a root level item for config_type. The config_type element leaves the door open for subsequent configurations like "mvc" that would require a different collection of generator keys to be present.

Here is a partial view of the template, for a full template checkout the default here:

{
    "config_type": "hexagonal",

    "model": {
        "template": "model.txt",
        "directory": "app/models",
        "filename": "{{Entity}}.php"
    },
    "controller": {
        "template": "controller.txt",
        "directory": "app/controllers",
        "filename": "{{Entities}}Controller.php"
    },
    "migration_create": {
        "template": "migration_create.txt",
        "directory": "app/database/migrations",
        "filename": "{{migration_timestamp}}_create_{{collection}}_table.php"
    },
    "view_show": {
        "template": "view_show.txt",
        "directory": "app/views/{{collection}}",
        "filename": "show.blade.php"
    },
}

The key take away here is that for each singular generator there are sub elements for template, directory, and filename.

  • template - the template file to use for this generator relative to the config file
  • directory - the directory where the final parsed template should be written, relative to the directory you were in when Blacksmith was executed.
  • filename - the filename the parsed template should be saved as

Note: if the destination directories do not exist Blacksmith will create them.

To skip a generator, set it's configuration to false. This can be useful to skip generating views when you're building an API.

    "migration_create": false,

You can also see in the partial config file example that you can use template variables provided by the generator in both the directory and filename values of the configuration.

## Templates

Blacksmith templates use Mustache syntax, otherwise they are just plain text files. See below for the available variables that can be used.

The variables made available for each generator can be used in the generator template file or within the JSON config file in the directory, and filename values.

## Template Variables ### Standard Variables

Each Blacksmith generator will always have the following standard variables available for use in the generator template or in the config's directory, and filename values.

Variable Description Output Example
Entity Singular studly cased entity name Order
Entities Plural studly cased entity name Orders
Base Studly cased directory path Order/Sub/Directory
Namespace Studly cased namespace Order\Sub\Directory
collection Plural underscore cased entity name orders
instance Singular underscore cased entity name order
fields Associative multi-dimensional array of field names and attributes ['name' => ['type' => 'string']]
year The current year 2014
### Generator Specific Variables

Generator specific variables may only be available in certain generators because the use is specific:

Variable Description Generators Output Example
headings Array of field names that can be used as table headings view_index
view_show
['name', 'age']
cells Array of code snippets that can be used to ouptut values in table cells view_index
view_show
["\$user->name", "\$user->age"]
mock_attributes Array of fields set with mock data functional_test ["'name' => 'dreamcatcher',",]
columns Array of schema builder column creation code snippets migration_create ["\$table->string('name');"]
migration_timestamp Timestamp used for migration filenames migration_create 2014_03_13_042956
form_rows Array of element + label Laravel form builder code for the passed in fields form see below

form_rows Output Example:

"{{ Form::text('name') }}" ] ] ">
[
    [
        'label' => "{{ Form::label('name', 'Name:') }}",
        'element' => "{{ Form::text('name') }}"
    ]
]

Note: with the exception of migration_timestamp all the generator specific variables are arrays. The content and count will vary as it is based on the --fields that were passed in.

## Intelligent Laravel Generators

Outside of template variables some of the generators have laravel specific actions that are taken after the template is generated and written out IF conditions are right. The table below describes each use case:

Generator Extra Functionality
migration_create Tests to see if app/database/seeds/DatabaseSeeder.php exists relative to the current directory. If so it checks that the newly generated seeder isn't already present in DatabaseSeeder.php. If the file exists, and entry is not present it will be added.
scaffold Tests to see if app/routes.php exists relative to the current directory. If so the routes file will be appended with a Route::resource() entry for the newly created resourceful controller.
Comments
  • Generate different class in the same directory

    Generate different class in the same directory

    Hi,

    This is a sample from my template config file.

    "controller": {
            "template": "controller.txt",
            "directory": "foo/bar/{{Entity}}/Controller",
            "filename": "{{Entity}}Controller.php"
        },
    

    Based on the README, if i run blacksmith generate Foo scaffold it will create a new controller inside foo/bar/User/Controller. My question is it possible for me to create another controller eg FoobarController.php and the file will be inside foo/bar/User/Controller directory. Because if I'm not mistaken the command will be blacksmith generate Foobar scaffold so the Entitiy will now be Foobar instead of Foo.

    opened by ahmadshah 6
  • add custom base directory support

    add custom base directory support

    Referring to issue #13

    Added support like @bkuhl suggested. This will enable to execute command like blacksmith generate Foo.Foobar scaffold ~/path/to/config.json. Also added a new template variable called {{Base}} to retrieve the base directory name

    Signed-off-by: Ahmad Shah Hafizan Hamidin [email protected]

    opened by ahmadshah 3
  • Is it possible to do a different config than hexagonal?

    Is it possible to do a different config than hexagonal?

    Am wondering how can I use a different type besides hexagonal and supplying different keys inside the config file.

    "config_type": "foobar"
    
    opened by ahmadshah 2
  • Exception when self-updating

    Exception when self-updating

    Even though I have the latest version, I was curious about the self updating mechanism and hit a snag. I see the following exception when updating. It looks like the below URL actually redirects to https://raw.githubusercontent.com/Indatus/blacksmith/master/blacksmith-manifest.json. Perhaps file_get_contents() doesn't like redirects?

    $ blacksmith self-update
    Looking for updates...
    
      [Herrera\Json\Exception\FileException]
      file_get_contents(https://github.com/Indatus/blacksmith/raw/master/blacksmith-manifest.json): failed to open stream: operation failed
    
    self-update [-p|--pre] [-r|--redo] [-u|--upgrade]
    
    bug 
    opened by bkuhl 2
  • Forcing regeneration

    Forcing regeneration

    • --f parameter now available to force regeneration
    • forcing regeneration in a laravel application does not duplicate routes
    • minor tweaks to hexagonal templates including adding parent::__construct() to constructors
    • added year template variable to documentation
    • exception is thrown when there's an invalid config path provided
    opened by bkuhl 1
  • InstanceInterface is not generated

    InstanceInterface is not generated

    There doesn't seem to be an Instances/InstanceInterface.php generated in Contracts within lib using the json config packaged with Blacksmith. Is this intentional or a bug?

    opened by bkuhl 1
  • 'Contracts\Notification\CreatorInterface' not found

    'Contracts\Notification\CreatorInterface' not found

    Symfony \ Component \ Debug \ Exception \ FatalErrorException
    Interface 'Contracts\Notification\CreatorInterface' not found
    open: /Users/foobar/your-project-name/app/controllers/UsersController.php
    use Contracts\Repositories\UserRepositoryInterface;
    use Contracts\Instances\InstanceInterface;
    use Contracts\Notification\CreatorInterface;
    use Contracts\Notification\UpdaterInterface;
    use Contracts\Notification\DestroyerInterface;
    use Validators\Validator as Validator;
    
    class UsersController extends BaseController implements CreatorInterface, UpdaterInterface, DestroyerInterface
    {
    
    
    opened by renege 1
  • Develop

    Develop

    • Updated phpdoc
    • Added "Getting Started" section to readme (outlines interfaces are not generated)
    • Added generators for creator, updater and destroyer tests
    • Added {{year}} variable
    opened by bkuhl 0
  • Posting Issues issue

    Posting Issues issue

    @devcflynn in #16 you suggested that your fork https://github.com/devcflynn/blacksmith should be used as you plan on actively developing this with Indatus going forward.

    Issues aren't turned on, and as I look to this project to potentially use in a personal workflow I have run into a few issues I would like to document as well as next steps I feel might be good to discuss or look into for the move to Laravel 5.

    Should I be posting those here? on your fork... or on mine? I started on mine but just discovered a few other pain points from the original implementation

    Also not sure it would actually stem from https://github.com/brianwebb01/hexagonal-laravel-experiment or this but the creationFailedValidation you use in the Creator isn't a part of the interface contract or initially implemented. As well as the delete method in the repositories which isn't initially implemented.

    opened by EHLOVader 0
  • Support for default configuration outside of phar

    Support for default configuration outside of phar

    Does this offer support for a default config.json in a templates folder or similar outside of the phar but relative to the current working directory?

    Could it? It would save from having to type the path in every command without having to aliasing it or recompiling this from a fork.

    opened by EHLOVader 1
  • Migration generator bug for decorators

    Migration generator bug for decorators

    this code blacksmith generate author scaffold ~/Desktop/blksm_cust_tpl/config.json --fields="name:string[50]"

    Generates this:

    public function up()
        {
            Schema::create('authors', function(Blueprint $table) {
                $table->increments('id');
                $table->string[50]('name');
                $table->timestamps();
            });
        }
    

    Should be:

    $table->string('name', 50);

    bug 
    opened by brianwebb01 0
Owner
Indatus
Indatus
A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm for each semester. All this served as a website.

Timetable-System-Generator A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm

null 3 Nov 19, 2022
Translate eloquent entity models

Translate entity About package This package is intended for adding multi language support to your models. If your application already be working and y

null 7 Aug 7, 2020
A code generation tool for Laravel developers.

Blueprint is an open-source tool for rapidly generating multiple Laravel components from a single, human readable definition. Watch a quick demo of Bl

Laravel Shift 2.4k Jan 5, 2023
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Mehrdad Mahdian 6 Sep 27, 2021
Localization Helper - Package for convenient work with Laravel's localization features and fast language files generation

Localization Helper Package for convenient work with Laravel's localization features and fast language files generation. Installation Via Composer $ c

Galymzhan Begimov 0 Jul 13, 2019
A simple package to manage the creation of a structure composed of the service and repository layers in a Laravel application

Chapolim Este projeto tem como objetivo fornecer alguns comandos adicionais à interface de linha de comando do Laravel, o Artisan, para manipular a es

Eliezer Alves 51 Dec 11, 2022
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
Allow your model to record the creation, update and deletion of user fingerprints in laravel packages

This laravel package will allow your models to record the the created, updated and deleted by User FingerPrints

Managemize 4 Mar 11, 2022
Migrator is a GUI migration manager for Laravel which you can create, manage and delete your migration.

Migrator Migrator is a GUI migration manager for Laravel which you can create, manage and delete your migration. Installation: To install Migrator you

Reza Amini 457 Jan 8, 2023
A laravel Livewire Dynamic Selects with multiple selects depending on each other values, with infinite levels and totally configurable.

Livewire Combobox: A dynamic selects for Laravel Livewire A Laravel Livewire multiple selects depending on each other values, with infinite levels of

Damián Aguilar 25 Oct 30, 2022
Shows the path of each blade file loaded in a template

Laravel Tracer Tracer shows the paths of all the Blade files that are loaded into your templates. This could be very convenient for a number of reason

Appstract 97 Oct 1, 2022
A Laravel 8 and Livewire 2 demo showing how to search and filter by tags, showing article and video counts for each tag (Polymorphic relationship)

Advanced search and filter with Laravel and Livewire A demo app using Laravel 8 and Livewire 2 showing how to implement a list of articles and tags, v

Sérgio Jardim 19 Aug 29, 2022
Laravel Common Password Validator

laravel-common-password-validator Laravel Common Password Validator An optimized and secure validator to check if a given password is too common. By d

WedgeHR 1 Nov 6, 2021
Tasty TADS 3 recipes for solving common and uncommon problems.

TADS 3 Cookbook Tasty TADS 3 recipes for solving common and uncommon problems when writing interactive fiction. There are two aspects of the TADS 3 Co

Jim Nelson 9 Apr 17, 2022
A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell

PHPAlgorithms A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDow

Doğan Can Uçar 921 Dec 18, 2022
A PHP package that provides common Data and Value Objects, that are Laravel castable.

Common Casts A PHP package that provides common Data and Value Objects, that are Laravel castable. Installation composer require juststeveking/common-

Steve McDougall 2 Sep 21, 2022
Manage your staff from one place. Featuring Staff leave management 🏖, payslips 💵 generation & emailing, messaging 📨and more 🛠! Built with ❤️ with Laravel

Staff Management System This little buddy can help you manage your staff database! Built with ?? with Laravel #FEATURES 1 Staff management/ database S

Ezekiel Oladejo 45 Jan 3, 2023
Création d'un livre d’or permettant aux utilisateurs de laisser leurs avis sur le site internet.

?? Livre d'or ?? // Création d'un livre d’or permettant aux utilisateurs de laisser leurs avis sur le site internet. // ?? Description du projet Créat

Alexandre DAUMAIL 0 Apr 4, 2022