Get model name php

PHP function to obtain model_name from Namespace\To\ModelName

\$\begingroup\$ Your question is a bit terse, and given your example the code doesn’t work. Could you give a real example? What does __CLASS__ contain and what is the output? What if there’s no namespace? \$\endgroup\$

\$\begingroup\$ @KIKOSoftware __CLASS__ would contain the name of the class, as this method is in a trait, it would depend on the class it’s used in. The class is always in a namespace, so accounting for it not being in one is not important. \$\endgroup\$

\$\begingroup\$ Can you provide a correct class name example? In other words: What will be contained in __CLASS__ ? \$\endgroup\$

5 Answers 5

You tagged laravel , so this answer assumes you are using Laravel.

Laravel has two built in helper functions that will help you do this. class_basename() will return the name of the class with the namespace stripped off, and snake_case() will convert a string to snake case.

public function getModelName()

\$\begingroup\$ I didn’t know about snake_case() . This looks like the cleanest solution. \$\endgroup\$

\$\begingroup\$ this is the best answer for my usecase, it’s clear to read, uses logic that’s already there, and it’s short. \$\endgroup\$

There’s actually not much I can do when it comes to efficiency, but it is clear that the code is not very readable. All these nested function calls make it very hard to track what’s going on.

My suggestion would be to split this single method into multiple methods. This is a very normal strategy in programming. A method should only do one thing, and do it well. This is also called the Single responsibility principle, and although this is usually applied to classes it can apply to methods as well.

Your code could look something like this:

public function getClassName() < // return class name only, without namespace, which must be present return substr(__CLASS__, strrpos(__CLASS__, '\\') + 1); >public function getClassNameWords() < // return an array of the words in the camel case class name return preg_split('/(?=[A-Z])/', lcfirst($this->getClassName())); > public function getModelName() < // return the name for the model as defined by the class name return strtolower(implode('_', $this->getClassNameWords())); > 

Each of these three functions is clearly shorter and easier to read. The extra methods allow you to reuse the code they contain. The code is no longer locked up in a single method.

Читайте также:  Прайс лист html примеры

I won’t go down the rabbit hole of debating what constitutes a «valid Pascal/Studly-cased string» but there is plenty of debate here if you want to read about fringe cases (like acronyms and multibyte characters). I will merely cross my fingers and hope that your project’s naming convention does not wonder into tricky territory. Either way, the post-namespace substring portion of my pattern can be easily amended to suit your input and desired output.

  1. Consume the namespace portion and omit it. My pattern matches zero or more sequences of not \\ then \\ .
  2. Then it matches a single uppercase letter followed by zero or more lowercase letters. (not very tricky)
  3. Inside of the custom callback function, I check if there is a namespace substring matched ( $m[1] ), if not I prepend an underscore.
  4. Finally, I convert the first letter of the matched classname word to lowercase and return the built string as the replacement value.
const testNamespacedClasses = [ "Namespace\To\SettingOption", "I\Was\Born\InTheUSAIwas", "Something\Onething" ]; function testSnakeCasedModelNames() < foreach (testNamespacedClasses as $class) < echo "$class =>"; echo preg_replace_callback( '~([^\\\\]*\\\\)*([A-Z][a-z]*)~', function($m) < return ($m[1] ? '' : '_') . lcfirst($m[2]); >, $class ); echo "\n---\n"; > > echo testSnakeCasedModelNames(); 
Namespace\To\SettingOption => setting_option --- I\Was\Born\InTheUSAIwas => in_the_u_s_a_iwas --- Something\Onething => onething --- 

To implement in your project:

public function getSnakeCasedModelName() < return preg_replace_callback( '~([^\\\\]*\\\\)*([A-Z][a-z]*)~', function($m) < return ($m[1] ? '' : '_') . lcfirst($m[2]); >, __CLASS__ ); > 

I considered using the \G metacharacter on this answer, but felt it overcomplicated the pattern and the desired result can be obtained without it

When comparing KIKO’s answer versus mine, consider if «abstraction» is beneficial to your project. It is completely plausible that it is. On the other hand if you don’t want to break the string manipulation process into its most basic parts, you can avoid the overhead of subsequent method calls. «Premature Abstraction» is a thing. It’s an academic point, but you should consider the impacts of either approach on maintainability, testing, overhead, code size, readability, etc. I don’t mean to say that there is anything wrong with KIKO’s advice — «single responsibility» is an important principle in writing professional-grade code.

Finally, because I am using a preg_ call to reformat the class string anyhow, I prefer to also use it to to remove the namespace. There are some benchmarks provided here which include a Reflection-based technique, but those benchmarks are only half of the job that you require.

If you are using __CLASS__ then I assume that you can also use __NAMESPACE__ which means that perhaps str_replace(__NAMESPACE__ . ‘\\’, __CLASS__) can be used to trim the namespace substring from the class. Since you are using Laravel, you can use its helper function: $baseClass = class_basename($className); . then you only need to convert StudlyCase to snake_case.

Источник

Php laravel get model name from table name

Then you can get table name with Solution 2: Here’s a slight modification so that you can get a model’s table name statically. Solution 2: You need to specify the table name inside the each Laravel model by using so in your case Solution 3: You may specify a custom table by defining a table property on your model:

Читайте также:  Python list remove objects

Laravel get Model by Table Name

Maybe something like this will help you:

$className = 'App\\' . studly_case(str_singular($tableName)); if(class_exists($className))

studly_case() and str_singular() are deprecated functions.

You can use the Illuminate\Support\Str facade.

$className = 'App\\' . Str::studly(Str::singular($tableName)); 

You must determine for which table name which class to call. I see 2 ways to do this.

Use some kind of dictionary

public function search($tableName) < $dictionary = [ 'table_name' =>'CLASS_NAME_WITH_NAMESPACE', 'another_table_name' => 'CLASS_NAME_WITH_NAMESPACE', ]; $className = $dictionary[$tableName]; $models = null; if(class_exists($className)) < $models = $className::all(); >// do some filtering, then return the model return $models; > 

Change laravel model table name, With the above setup I do not get any records from the table though table has data. How do I change table of the model ? php laravel eloquent

How can I get table name, statically from Eloquent model?

You can add to your model.

public static function getTableName() < return (new self())->getTable(); > 

Then you can get table name with Something::getTableName()

Here’s a slight modification so that you can get a model’s table name statically.

  1. On your other models, you can set the custom table name on Laravel’s reserved attribute: protected $table

Usage : just call YourModel::tableName() anywhere.

DB::table( Product::tableName() . ' AS p' ) ->leftJoin( ProductCategory::tableName() . ' AS pc', 'pc.id', '=', 'p.category_id') // . etc 

Not static but elegant approach

with(new Something)->getTable(); 

Laravel model add table name Code Example, how does laravel create table name · set table name in model laravlw · create table laravel with value · custom table name laravel eloquent

How to change Laravel model’s table name

If you don’t want to use the default table name ( the «snake case», plural name of the class ), you should specify it to the model :

protected $table = 'DomainRelatedSettings'; 

Check the documentation at the Table Names section.

You need to specify the table name inside the each Laravel model by using

protected $table = 'name_of_table'; 
protected $table = 'DomainRelatedSettings'; 

You may specify a custom table by defining a table property on your model:

class theModel extends Model < /** * The table associated with the model. * * @var string */ protected $table = 'name_of_table'; >

In case it doesn’t work, try typing this command inside from your root folder: composer dump-autoload -o

Define table name in laravel model, Why where fa_test . deleted_at is null deleted from my query? laravel laravel-5 model eloquent localization.

Laravel: passing dynamic table name to model e.g protected $table = «$tablename»

better to use fluent query builder db

u can add dynamically table name with insert,update,read,delete operation

 DB::table($tableName)->insert(['name' => $name]); 

for automatically added created_at and updated_at add in migration

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')); 

Change model And database table name in Laravel, you can set per model the table or the connexion to use via protected attributes of the model: laravel.com/docs/8.x/eloquent#table-names. – N69S.

Читайте также:  Название страницы

Источник

php — Getting model name from model instance YII

Solution:

add this method to your State Class

public function getModelName() 
$model = new State(); echo $model->getModelName(); 

Answer

Solution:

get_class() — Returns the name of the class of an object

string get_class ([ object $object ] )

therefore you use it like this: $modelname=get_class($modelinstance);

Answer

Solution:

Use this PHP method : get_class

 print get_class($object); 

Answer

Solution:

 public function getCalledClassName() < return get_called_class(); >> class Product extends Item <> class Service extends Item <> class ProductController extends CController < $model = new Product; echo $model->baseModelName; // Item > class ServiceController extends CController < $model = new Service; echo $model->calledClassName; // Service echo get_class($model); // Service > 

Answer

Solution:

To get State as the question asked, you may do this : —

basename(get_class($model)) 

Share solution ↓

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Yii

Yii is a simple yet high performance generic component framework based framework. It is known for its high performance, but above all, it is famous for its simplicity. This framework appeared in December 2008. It allows you to use third-party code, and its Gii code generator allows you to quickly create basic structures from which you can build your own solutions.
https://www.yiiframework.com/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Оцените статью