bentools/helpfultraits
Deprecated, unmaintained repository of small PHP helper traits. No longer maintained and may be removed soon; consider forking if you still depend on it.
Installation Add the package via Composer (if still available or forked):
composer require bpolaszek/helpfultraits
If archived, fork the repo and install via:
composer require your-fork/helpfultraits
First Use Case
The package provides traits for common Symfony/Laravel utilities. Start with the ArrayTrait for array manipulation:
use Bentools\HelpfulTraits\ArrayTrait;
class MyService {
use ArrayTrait;
public function processData() {
$data = ['a' => 1, 'b' => 2];
$flattened = $this->flatten($data); // Returns [1, 2]
}
}
Key Traits to Explore
ArrayTrait: Methods like flatten(), pluck(), dot().StringTrait: String utilities (e.g., slugify()).CollectionTrait: Laravel Collection helpers (e.g., groupBy()).DateTrait: Date formatting/manipulation.Check the source code for full method lists.
Array Manipulation
Use ArrayTrait for nested array operations in controllers/services:
use Bentools\HelpfulTraits\ArrayTrait;
class DataProcessor {
use ArrayTrait;
public function transform(Request $request) {
$input = $request->all();
$flattened = $this->flatten($input, '.'); // Dot notation
return $this->pluck($flattened, 'user.*'); // Extract nested keys
}
}
String Utilities Sanitize/slugify strings in models or form requests:
use Bentools\HelpfulTraits\StringTrait;
class PostRequest {
use StringTrait;
public function prepareForValidation() {
$this->merge([
'slug' => $this->slugify($this->title),
]);
}
}
Date Handling Format dates consistently across the app:
use Bentools\HelpfulTraits\DateTrait;
class ReportGenerator {
use DateTrait;
public function generate() {
$formatted = $this->formatDate(now(), 'Y-m-d H:i:s');
return $this->parseDate($formatted, 'd/m/Y'); // Convert formats
}
}
Collection Helpers Extend Laravel Collections with custom logic:
use Bentools\HelpfulTraits\CollectionTrait;
class UserService {
use CollectionTrait;
public function getActiveUsers() {
return User::query()
->get()
->filterBy('active', true) // Custom method
->groupBy('role');
}
}
collect()->flatten()) where possible.$mock = $this->getMockBuilder(MyService::class)
->onlyMethods(['flatten'])
->getMock();
Deprecation Risk
Symfony\Component\HttpFoundation\Request references with newer versions.Method Overrides
pluck()). Rename or alias:
// In a trait
public function customPluck($key) {
return $this->pluck($key); // Original method
}
Performance
flatten()) may be slow for large arrays. Benchmark against native alternatives:
// Compare:
$this->flatten($array); // Trait
collect($array)->flatten()->all(); // Native
Type Safety
slugify() return string, but input validation is not enforced. Add guards:
public function slugify($string) {
if (!is_string($string)) {
throw new \InvalidArgumentException('Input must be a string');
}
return parent::slugify($string);
}
Trait Method Not Found?
Ensure the trait is used correctly and the class isn’t final. Verify the method exists in the source.
Symfony Dependency Errors If using Laravel, some traits assume Symfony components. Override or mock:
// Example: Mock Request in tests
$this->app->instance('request', Request::create('/'));
Customize Methods Extend traits in your own classes:
trait ExtendedArrayTrait {
use \Bentools\HelpfulTraits\ArrayTrait;
public function customMerge(array $array, $glue = '.') {
return $this->merge($array, $glue) + ['custom' => 'value'];
}
}
Add New Traits
Fork the repo and add your own (e.g., JsonTrait for JSON utilities):
trait JsonTrait {
public function jsonPath($json, $path) {
return json_decode($json, true)[$path] ?? null;
}
}
Configuration No config file exists. Use dependency injection or environment variables for shared values:
// In a service
public function __construct(private string $defaultSlugSeparator = '-') {}
public function slugify(string $string): string {
return str_replace(' ', $this->defaultSlugSeparator, $string);
}
Laravel-Specific Optimizations Combine with Laravel’s built-ins for cleaner code:
use Bentools\HelpfulTraits\{ArrayTrait, CollectionTrait};
class OrderService {
use ArrayTrait, CollectionTrait;
public function processOrder(array $data) {
$items = collect($this->flatten($data['items']));
return $items->filterBy('quantity', '>', 0)->values();
}
}
Documentation Since the package lacks docs, add PHPDoc blocks to traits for IDE support:
/**
* Flattens a nested array with custom separator.
*
* @param array $array
* @param string $separator
* @return array
*/
public function flatten(array $array, string $separator = ''): array
How can I help you explore Laravel packages today?