Skip to content

Instantly share code, notes, and snippets.

@jtgrimes
Created August 2, 2021 16:34
Show Gist options
  • Save jtgrimes/3e5c50eef8929824a1a6f4694497f828 to your computer and use it in GitHub Desktop.
Save jtgrimes/3e5c50eef8929824a1a6f4694497f828 to your computer and use it in GitHub Desktop.
php/js consts
// This is the code in the script to generate the file...
protected $signature = 'generate:constants';
protected $description = 'Generate json files for constants';
protected $outputFile = 'resources/js/plugins/constsPlugin.js';
public function handle()
{
// clear any existing file
if (is_file(base_path($this->outputFile))) {
unlink(base_path($this->outputFile));
}
file_put_contents($this->outputFile, $this->getJSTemplate(Constants::toJson()));
return 0;
}
private function getJSTemplate($constants)
{
return <<< EOT
// This file is generated. DO NOT EDIT. Add/modify constants in the /app/Constants.php file instead.
const CONSTS = $constants;
CONSTS.install = function (Vue, options) {
Vue.prototype.\$const = (key) => {
return CONSTS[key];
};
};
export default CONSTS;
EOT;
}
// and this is the Constants class:
<?php
namespace App;
class Constants
{
protected static $imports = [
User::class,
Activity::class,
];
// Laravel models
...
const TAG_MODEL = Tag::class;
const USER_MODEL = User::class;
// Page Type
const PAGE_HOME = "home";
const PAGE_LANDING = "landing";
...
public static function toJson()
{
$constants = collect(self::getClassConstants(self::class));
foreach (self::$imports as $class) {
$constants = $constants->merge(self::getClassConstants($class));
}
return json_encode($constants, JSON_PRETTY_PRINT);
}
private static function getClassConstants($class)
{
$reflector = new \ReflectionClass($class);
return $reflector->getConstants();
}
}
// so the constants class has a list of classes to import constants from as well as its own "global" type constants.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment