Helpers & Services

[Since 0.5.0]

TODO: Anpassen

Introduction

Out of the box, Pletfix provides a collection of functions for accessing the services that are bound in the Dependency Injection Container. The functions are defined in vendor/pletfix/core/functions/services.php.

Additional helper function are defined in vendor/pletfix/core/functions/helpers.php.

You are free to use them in your own applications if you find them convenient.

Source hints

The pluraland singular functions are based on Laravel's [Str class](https://github.com/illuminate/support/blob/5.3/Str.php Laravel's Str) and Laravel's Pluralizer, which again used the Doctrine's [Inflector](https://github.com/doctrine/inflector/tree/1.1.x Doctrine's), licensed under the MIT License.

pascal_case, limit_string, slug and utf8_to_ascii are copied from Laravel's [Str class](https://github.com/illuminate/support/blob/5.3/Str.php Laravel's Str). The Laravel framework is open-sourced software licensed under the MIT license.

$charsArray of the utf8_to_ascii method is adapted from Stringy by Daniel St. Jules, licensed under the MIT License.

Available Methods

Paths

Strings

Miscellaneous

Services

Method Listing

Paths

app_path()

The app_path function returns the fully qualified path to the app directory. You may also use the app_path function to generate a fully qualified path to a file relative to the application directory:

$path = app_path();

$file = app_path('Http/Controllers/Controller.php');

base_path()

The base_path function returns the fully qualified path to the project root. You may also use the base_path function to generate a fully qualified path to a given file relative to the project root directory:

$path = base_path();

$path = base_path('vendor/bin');

config_path()

The config_path function returns the fully qualified path to the application configuration directory:

$path = config_path();

manifest_path()

The manifest_path function returns the fully qualified path to the hidden manifest folder:

$path = manifest_path();

public_path()

The public_path function returns the fully qualified path to the public directory: You may also use the public_path function to generate a fully qualified path to a given file relative to the public directory:

$path = public_path();

$file = public_path('images/logo.png');

resource_path()

The resource_path function returns the fully qualified path to the resources directory. You may also use the resource_path function to generate a fully qualified path to a given file relative to the resources directory:

$path = resource_path();

$file = resource_path('assets/sass/app.scss');

storage_path()

The storage_path function returns the fully qualified path to the writable storage directory. You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$path = storage_path();

$file = storage_path('app/file.txt');

vendor_path()

The vendor_path function returns the fully qualified path to the vendor directory. You may also use the vendor_path function to generate a fully qualified path to a given file relative to the vendor directory:

$path = vendor_path();

$file = vendor_path('npm-asset/jquery/dist/jquery.min.js');

workbench_path()

The workbench_path function returns the fully qualified path to the workbench directory. You may also use the workbench_path function to generate a fully qualified path to a given file relative to the workbench directory:

$path = workbench_path();

$file = workbench_path('npm-asset/jquery/dist/jquery.min.js');

Strings

plural

Get the plural form of an english word.

$s = plural('person'); // people

singular()

Get the singular form of an english word.

$s = singular('children'); // child

camel_case()

Converts a word to camel case (camelCase).

This is useful to convert a word into the format for a variable or method name.

$s = camel_case('Cogito ergo sum'); // cogitoErgoSum

lower_case()

Convert the given word to lower case.

$s = lower_case('Cogito ergo sum'); // cogito ergo sum

pascal_case()

Converts the given word to pascal case, also known as studly caps case (PascalCase).

This is useful to convert a word into the format for a class name.

$s = pascal_case('Cogito ergo sum'); // CogitoErgoSum

random_string()

The random_string generates cryptographically secure pseudo-random alpha-numeric string.

$token = random_string(40); // 6L1oKbruRg71YT4bjtsgdndxVQzXn8dUNHIrTQql

snake_case()

Convert the given word to snake case (snake_case).

This is useful to converts a word into the format for a table or a global function name.

$s = snake_case('CogitoErgoSum'); // cogito_ergo_sum

title_case()

Convert the given word to title case (Title Case).

$s = title_case('Cogito ergo sum'); // Cogito Ergo Sum

upper_case()

Convert the given word to upper case.

$s = upper_case('Cogito ergo sum'); // COGITO ERGO SUM

limit_string()

Limit the number of characters in a string.

$s = limit_string('If you can dream it, you can do it.', 20); // If you can dream it,...

slug()

Generate a URL friendly "slug" from a given string.

$s = slug('If you can dream it, you can do it.'); // if-you-can-dream-it-you-can-do-it

utf8_to_ascii()

Transliterate a UTF-8 value to ASCII.

$s = utf8_to_ascii('© 2017'); // (c) 2017

Miscellaneous

abort()

The abort function throws a HTTP exception which will be rendered by the exception handler:

abort(Response::HTTP_UNAUTHORIZED);

You may also provide the exception's response text:

abort(Response::HTTP_UNAUTHORIZED, 'Unauthorized.');

asset()

The asset function generates the URL to an application asset.

<script src="{{ asset('js/app.js') }}"></script>

benchmark()

The benchmark function prints the elapsed time in milliseconds and the memory usage in bytes that the callback function needs:

benchmark(function($loop) {
    // your test code
});

You can specify the number of calls in the second argument. Furthermore, if you set the third argument to true, benchmark() will return the information rather than print it:

$result = benchmark(function($loop) {
    // your test code
}, 100, true);    

bcrypt()

The bcrypt function creates a password hash using the CRYPT_BLOWFISH algorithm.

$hash = bcrypt('psss...');  

canonical_url()

The canonical_url() method always returns the same URL for a particular page, even if the page is accessible through different URLs. To do this, the base URL from the configuration config('app.url')and the path of the actual request are joined together (without any parameters).

Furthermore, if your application is multilingual, this function prefixes the path with the current language code. Be sure the corresponding route entry exists!

For example if we have a request http://www.example.com/path?a=3, the canonical_url could be https://example.de/path/en.

This URL is very important for SEO (Search Engine Optimizing), see the article Use canonical URLs by Googles Help Forum for more details.

The following link sets the Canonical URL for a page:

 <link rel="canonical" href="@yield('canonical-url', canonical_url())"/>

command()

The command function runs a console command by name.:

command('migrate', ['-r']);

config()

The config function gets the value of a configuration variable.

The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access:

$timezone = config('app.timezone');

A default value may be specified and is returned if the configuration option does not exist:

$debugMode = config('app.debug', 'false'); 

csrf_token()

The csrf_token function gets the session's CSRF token value. It's useful for the a web form:

<input type="hidden" name="_token" value="{{csrf_token()}}"/> 

The CSRF token is stored in the session under the `'_csrf_token'´ key.

dump()

The dump function dumps the given variables:

dump($value);

If you set the second argument to true, dump() will return the information rather than print it:

$dump = dump($value, true);

dd()

The dd function dumps the given variables and ends execution of the script:

dd($value);

If you do not want to halt the execution of your script, use the dump function instead.

e()

The e function runs htmlspecialchars over the given string:

echo e('<html>foo</html>');

// &lt;html&gt;foo&lt;/html&gt;

This function is called too if you echo a variable in a blade template with the normal echo tags:

{{ $var }}     

env()

The env function gets the value of an environment variable or returns a default value:

$env = env('APP_ENV');

// Return a default value if the variable doesn't exist...
$env = env('APP_ENV', 'production');

IMPORTANT: If the config was cached the environment file ".env" is not read. Therefore you should never use this function directly, instead only in the configuration files.

error()

The error function retrieves an error message from the flash for the given key:

$error = error('email');

error() is a shortcut for:

$error = flash()->get('errors.' . $key)        

You can set the error message with the withError or withErrors method of the Response object.

guess_file_extension()

The guess_file_extension function returns the file extension based on the mime type. If the mime type is unknown, returns false.

$ext = guess_file_extension('image/gif'); // 'gif'

http_status_text()

The http_status_text function translates a HTTP Status code to plain text:

echo http_status_text(Response::HTTP_BAD_REQUEST);

is_absolute_path()

The is_absolute_path function determines if the given path given is an absolute path:

$isAbs = is_absolute_path('/tmp');

is_active()

The is_active function determines if the given path is the one of the current url.

<li {!! is_active('abort') ? 'class="active"' : '' !!}>
    <a href="{{url('abort')}}"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> About</a>
</li>

is_console()

The is_console function determines if we are running in the console:

if (is_console()) {
    echo 'This is a console!';
}

is_supported_locale()

The is_supported_locale function determines if the given language code is supported by the application:

if (is_supported_locale('de')) {
    echo 'The application speaks German.';
}

You can specify the supported languages in the configuration file config/locale.php.

is_multilingual()

The is_multilingual function determines if the application is multilingual:

$isMultilang = is_multilingual();

The function returns true, if more as one language is supported, specified in the configuration file config/locale.php.

is_testing()

The is_testing function determines if we are running unit tests.

if (is_testing()) {
    echo 'The environment variable APP_ENV is set to "testing".';
}

is_windows()

The is_windows function determines if the os is windows:

$win = is_windows();

list_files()

The list_files function reads files recursive:

list_files($result, $path);

list_classes()

The list_classes function reads available PHP classes recursive from given path:

list_classes($result, app_path('Commands'), 'App\Commands');

locale()

The locale function gets and sets the current locale from and to the cookie:

locale('fr');

$locale = locale();

The argument must be a two-letter language code according to ISO 639-1. The function does not validate the code. Be sure the language is supported by the application. You can check this with the function is_supported_locale().

locale_url()

The locale_url function prefixes the path of the current URL with the given language code.

locale_url('fr');

The argument must be a two-letter language code according to ISO 639-1.

mail_address()

The mail_address function gets the email address without the name:

$email = mail_address('Webmailer <mail@example.com>'); // "mail@example.com"

make_dir()

The make_dir function creates a folder recursive:

make_dir(storage_path('temp'), 0777);

message()

The message function retrieves an message from the flash:

message()

message() is a shortcut for:

flash()->get('message')

See also withMessage method of Response object.

old()

The old function retrieves an old input item from the flash. It is useful in a web form:

<input type="email" id="email" name="email" value="{{old('email')}}"/>

old() is a shortcut for:

flash()->get('input' . $key)

See also withInput method of Response object.

redirect()

The redirect function returns a redirect HTTP response to the given path. The path should be relative to request()->baseUrl():

$redirect = redirect('home');

If you wish you could set GET parameters as second argument:

$redirect = redirect('home', ['name' => 'Peter']);

The default HTTP status is 302 for a temporarily link. You can create a permanently redirect link like this:

$redirect = redirect('home', ['name' => 'Peter'], 301);   

remove_dir()

The remove_dir function deletes a folder (or file). The folder does not have to be empty.

remove_dir(storage_path('temp'));

t()

The t function translates the given language line using your localization:

echo t('validation.required');

url()

The url function generates a absolute URL to the given path.

$url = url('public/images/logo.png');

Services

asset_manager()

The asset_manager function gets the AssetManager instance:

$assetManager = asset_manager()

Typically, you do not need access the Asset Manager programmatically. Instead, use the Pletfix console command 'asset'.

auth()

The auth function gets the Auth object:

$auth = auth();

cache()

The cache function retrieves the Cache instance for the given store:

$cache = cache($store);

collect()

The collect function creates a Collection instance:

$collect = collect(['red', 'yellow', 'green']);

cookie()

The cookie function creates a Cookie instance:

cookie()->set('foo', 'bar', 1440);

$foo = cookie()->get('foo');

database()

The database function retrieves the Database instance for the given store:

$db = database(); // default store

$db = database('testdb'); // store defined in config/database.php  

datetime()

The datetime function creates a advanced DateTime instance:

$now = datetime();

$christmas = datetime('2017-12-24');

di()

The di function retrieves the Dependency Injector instance:

$di = di();

http_client()

The http_client function creates a HTTP Client to send a request e.g. to a REST service:

$result = http_client()->post('service-url', ['id' => 4711]);

logger()

The logger function retrieves the Logger instance:

logger()->log('debug', $message);

mailer()

The mailer function retrieves the Mailer instance:

mailer()->send($to, $cc, $bcc, $subject, $body, $attachments);

migrator()

The migrator function retrieves the Migrator instance for the given store:

$migrator = migrator($store)

Typically, you do not need access the Migrator programmatically. Instead, use the Pletfix console command 'migrate'.

mime_type()

The mime_type function gets the MIME Type of the given file. Returns false, if the file does not exist or the mime type is unknown.

$mime = mime_type(storage_path('upload/image123.gif'));

paginator()

The paginator function creates a Paginator instance for generating pagination controls, typical used in an index action:

public function index()
{
    $builder   = User::builder();
    $paginator = paginator($builder->count());
    $users     = $builder->offset($paginator->offset())->limit($paginator->limit())->all();

    return view('admin.users.index', compact('paginator', 'users'));
}

plugin_manager()

The plugin_manager function creates a PluginManager instance for the given package:

$pluginManager = plugin_manager($package)

Typically, you do not need access the Plugin Manager programmatically. Instead, use the Pletfix console command 'plugin'.

process()

The process function creates a Process instance:

$process = process('ls -l')

a name="method-request">

request()

The request function retrieves the Request instance:

$request = request()

response()

The response function retrieves the Response instance:

return response()->output('Hello World', 200, $headers);

session()

The session function retrieves the Session instance:

$session = session();

If you read a specify value from the session, you may do it like this:

$value = session('key', 'default');

stdio()

The stdio function retrieves the Stdio instance for the Pletfix console:

$stdio = return stdio();

view()

Create a response with the given View.

return view('welcome', ['name' => 'Frank']);

If no arguments are passed, the function returns a new View instance. So, the example below is the same like above:

$output = view()->render('welcome', ['name' => 'Frank']);

return $this->output($output);

(edit on GitHub)